diff --git a/docs/API_PRODUCT_SUBSCRIPTION_PLAN.md b/docs/API_PRODUCT_SUBSCRIPTION_PLAN.md index 6fd48de615..71d60b4cfb 100644 --- a/docs/API_PRODUCT_SUBSCRIPTION_PLAN.md +++ b/docs/API_PRODUCT_SUBSCRIPTION_PLAN.md @@ -1,7 +1,7 @@ # API Product Subscription — making API Products enforceable Written 2026-09-02, revised 2026-09-02 after checking every code reference against the repo. -Track progress here by marking items done in place. **Status: Phases 0 to 3 coded and green on 2026-09-02 (`ApiProductSubscriptionTest` 9 scenarios, `RateLimitsTest` 12, `CacheKeyFormatTest` 5). Not yet committed. Phase 4 is other repos.** +Track progress here by marking items done in place. **Status: Phases 0 to 3 coded and green on 2026-09-02 (`ApiProductSubscriptionTest` 9 scenarios, `RateLimitsTest` 12, `CacheKeyFormatTest` 5), committed as "Product Subscriptions". Phase 4 (other repos): OBP-Stripe, Portal and API Manager done on 2026-11-17, not yet tested against a real OBP-API and Stripe; Portal usage panel waits for owner-gated usage endpoints; OBP-Billing not started.** Background: `../../commands/NMB_legal_2026/FROM_CLAUDE_plans_evolution_OBP_Stripe_OBP_Billing.md` (relative to this repo; the `commands` directory sits next to `OBP-API-Simon` in `workspace_2024`). @@ -245,7 +245,7 @@ Four actors. Ownership means `Consumer.createdByUserId == caller.userId`, exactl |---|---|---| | **developer** | owns the consumer; no role | subscribe own consumer; read own subscriptions and their attributes; set status `cancelled` on own subscription. Nothing else. | | **bank admin** | `…AtOneBank` roles at the product's bank | everything at that bank: subscribe any consumer, read all, any status transition, delete, write attributes. Typical use: approve `requested` → `active`, suspend, reinstate. | -| **billing adapter** | service account with `…AtOneBank` roles at every bank it serves (one Stripe or Invoice Ninja instance may serve several) | status transitions and attribute writes at those banks. In practice only `active`, `past_due`, `cancelled`. | +| **billing adapter** | a Platform App acting as itself (client credentials), with `…AtOneBank` Scopes at every bank it serves (one Stripe or Invoice Ninja instance may serve several) | status transitions and attribute writes at those banks. In practice only `active`, `past_due`, `cancelled`. | | **support / auditor** | `CanGetApiProductSubscriptionAtOneBank` | read only. | Roles: @@ -365,14 +365,37 @@ Requires Phase 1. ## Phase 4 — Adapters (other repos, listed for completeness) -- [ ] OBP-Stripe: read products with `BILLING_SYSTEM=stripe` from `GET /obp/v6.0.0/api-products`, - sync to Stripe Products/Prices (lookup_key = `bank_id:api_product_code`), create the OBP - subscription before checkout, put `api_product_subscription_id` in checkout and subscription - metadata, store `STRIPE_SUBSCRIPTION_ID` as a subscription attribute, and on webhooks PUT status - only. Delete the `CanCreateBank` and user-attribute provisioning code. +- [x] OBP-Stripe (2026-11-17, rewritten; see its README): a Platform App, no DirectLogin. It + reads products with `BILLING_SYSTEM=stripe` (`GET /obp/v6.0.0/api-products`, then each product for + its attributes) and keeps a monthly Stripe Price per product under lookup_key + `bank_id:api_product_code` (a changed amount creates a new Price and archives the old one). The + Portal creates the subscription; for a `stripe` product it stays `requested` and the Portal sends + the developer to OBP-Stripe `/checkout?api_product_subscription_id=ID`, which checks ownership + through `GET /my/api-product-subscriptions/ID` and starts Stripe Checkout with the subscription's + ids in the Checkout and Stripe subscription metadata. Webhooks and a 5-minute sync apply the Stripe + subscription's state by PUT status only: `active`/`trialing` → `active` (from `requested` or + `past_due`), `past_due` → `past_due`, `unpaid` → `suspended`, `canceled` → `cancelled`. It never + reinstates `suspended` (an admin may have suspended it). A subscription cancelled or deleted in OBP + is cancelled in Stripe. It stores `STRIPE_SUBSCRIPTION_ID` as a subscription attribute and + `STRIPE_CUSTOMER_ID` as the payer's non-personal user attribute. Scopes it declares: + `CanGetNonPersonalUserAttributes`, `CanCreateNonPersonalUserAttribute` (system); + `CanGetApiProductSubscriptionAtOneBank`, `CanUpdateApiProductSubscriptionStatusAtOneBank`, + `CanCreateApiProductSubscriptionAttributeAtOneBank` at each bank with a Stripe product; optional + `CanGetApiProduct` at each bank with products. The `CanCreateBank` and user-attribute provisioning + code is gone. Dockerfile and `k8s/` manifests added. - [ ] OBP-Billing: invoice per active subscription with `BILLING_SYSTEM=invoice_ninja` (monthly amount + overage from aggregate metrics); add the overdue loop that PUTs `past_due` / `active`. -- [ ] Portal: catalogue from `GET /api-products`, product detail page, usage panel from +- [x] Portal and API Manager (2026-11-17): the Portal subscribes, and for a `stripe` product sends + the developer to `PUBLIC_SUBSCRIPTIONS_URL/checkout?api_product_subscription_id=ID` (OBP-Stripe); + `requested` Stripe subscriptions get Pay, `active`/`past_due` get Manage billing. The old + account-application checkout route and `STRIPE_CHECKOUT_URL` are gone. The API Manager product page + lists subscriptions with Approve / Suspend / Reinstate / Cancel / Delete and an Enrol form for + `SELF_SUBSCRIBE=false` products; the consumer page lists a consumer's subscriptions. +- [ ] Portal usage panel: blocked. `call-counters` and `active-rate-limits` exist only as v6.0.0 + `/management/consumers/CONSUMER_ID/...` with `CanGetRateLimits`, which a fintech must not need. + Needs owner-gated `GET /my/consumers/CONSUMER_ID/call-counters` and `.../active-rate-limits` + (v7.0.0, no Role, 404 for a consumer the caller does not own). +- [x] Portal (the original item; catalogue and product pages exist, the usage panel is tracked above): catalogue from `GET /api-products`, product detail page, usage panel from `call-counters` and `active-rate-limits`. The fintech never needs a role; the product's attributes pick the button: diff --git a/ideas/ASSET_REGISTRY.md b/ideas/ASSET_REGISTRY.md index 44b338ef59..9e1c55b34d 100644 --- a/ideas/ASSET_REGISTRY.md +++ b/ideas/ASSET_REGISTRY.md @@ -1,6 +1,24 @@ # Draft v4: Asset Registry -**Status**: partly implemented. The registry exists, is seeded, and decides which currency codes are accepted and their decimal places, giving the same answers as the built-in list it replaced. The only changes callers can see so far are two attribute types (`DECIMAL`, `BOOLEAN`) and an amount too large to store being refused instead of wrapped. The progress section below lists what is built and what is next; section 12 records how the questions it raised were settled. +**Status (2026-11-18)**: partly implemented. Steps 1 to 9 are built and committed; the last commit was on 2026-10-29. Nothing has been started since, and no decision is waiting: every open question was settled on 2026-10-20 (section 12). + +What callers can do now: +- read the registry with no login (`GET /assets`, `GET /assets/ASSET_CODE` and the reverse chain lookup); +- register an asset with Create Asset: a bank registers an asset it issues, such as a `STABLECOIN`, and `SYS` registers a `CRYPTO` asset. The new code is accepted in `currency` fields at once; +- send currency codes in any letter case; +- expect an amount with more decimal places than its currency allows to be refused with 400, not cut off. + +What a bank still cannot do, in the order proposed: +1. **Use a new asset on every node at once.** Each node keeps the registry in memory, and Create Asset clears only its own copy (`AssetLookup.invalidate`). On a deployment with several nodes, the others refuse the new code until they restart. +2. **Freeze or suspend an asset.** The status endpoint and status history (§6, §8) are not built, so an issuer cannot stop its coin being used. +3. **Hold token amounts exactly.** Amounts are still stored as `Long` minor units (§5). At 18 decimal places a `Long` holds only about 9.2 units, so a token with many decimal places cannot be held in useful amounts. +4. **Update or delete an asset** (§8). +5. **Rely on correct precision for every code.** Some ISO codes and every crypto asset still have the built-in decimal places (§7 Part B). Run the step 2 report against a copy of production data first. +6. **Use `ADA` and `ETH` alone.** `lovelace` and `wei` are still separate codes (§7 Part C). + +Minting and burning on a chain is not part of this work. It belongs to the bank node (the TEuro repository). + +The progress section below gives the detail of each step. **Changes in v4 (2026-10-05)**: adds the progress section. `chain_scheme` names the network as well as the chain (§2); questions 10 and 11 are new. Records what the implementation settled or exposed: the seed has no switch (question 6), Mapper cannot declare the partial unique indexes (§2), the 4–10 character rule for non-seeded codes is not enforced yet (§3), the test setup empties the registry between tests (§11), and the unused `MappedCurrency` table (§11). Code references are brought up to date. @@ -61,8 +79,13 @@ The work is ordered so that each step changes nothing a caller can see until the | 6 | `isValidCurrencyISOCode` and `currencyDecimalPlaces` read from the registry (§4) | Done (`b4ac8c374`) | | 7 | Case-insensitive codes (§4): codes upper-cased in requests by `ResourceDocMiddleware`, compared ignoring case | Done (`8763728f6`) | | 8 | Rejecting excess decimals (§4): 400 (OBP-10068) from `ResourceDocMiddleware`, crypto assets exempt until §7 | Done (`91289dbf0`) | -| 9 | Create Asset, `POST /banks/BANK_ID/assets` (§8) | Done, not committed | -| Later | the other write endpoints (§8), amount storage (§5, §7 Part A), precision corrections (§7 Part B), folding `lovelace` and `wei` (§7 Part C, §10) | Each changes behaviour; the open questions they waited on are settled (§12) | +| 9 | Create Asset, `POST /banks/BANK_ID/assets` (§8) | Done (`fc8587455`; rules checked before conflicts in `c3fca5107`) | +| 10 | Registry cache that expires on every node after a write (step 6) | Not started; needed now that Create Asset writes | +| 11 | Update Asset Status and Get Asset Status History (§6, §8) | Not started | +| 12 | Amount storage as exact decimals (§5, §7 Part A) | Not started | +| 13 | Update Asset and Delete Asset (§8) | Not started | +| 14 | Precision corrections (§7 Part B) | Not started; run the step 2 report on real data first | +| 15 | Folding `lovelace` and `wei` into `ADA` and `ETH` (§7 Part C, §10) | Not started | **Step 1.** `CurrencyHandlingTest` is a pure unit test (no server, no database). It asserts correct behaviour only. The three known defects are written as the correct expectation inside `pendingUntilFixed`, so they report as pending now and fail, demanding the wrapper's removal, once fixed: - codes are not accepted in every letter case; diff --git a/obp-api/src/main/resources/docs/introductory_system_documentation.md b/obp-api/src/main/resources/docs/introductory_system_documentation.md index cb090e5ede..18fb8e8719 100644 --- a/obp-api/src/main/resources/docs/introductory_system_documentation.md +++ b/obp-api/src/main/resources/docs/introductory_system_documentation.md @@ -33,6 +33,7 @@ For more detailed information or the sources of truths, please refer to the indi - 3.15 [OBP Bank Node](#315-obp-bank-node) - 3.16 [OBP Cohort](#316-obp-cohort) - 3.17 [Conformator](#317-conformator) + - 3.18 [OBP-Stripe](#318-obp-stripe) 4. [Standards Compliance](#standards-compliance) 5. [Installation and Configuration](#installation-and-configuration) 6. [Migration Scripts and Migration Script Logs](#migration-scripts-and-migration-script-logs) @@ -124,6 +125,7 @@ The Open Bank Project (OBP) is an open-source RESTful API platform for banks tha - **Product Collections**: Group products into collections - **Fee Management**: Product fees, charges, pricing information - **Product Catalog**: Searchable product offerings +- **API Products and Subscriptions** (v7.0.0): an API Product is a plan for applications: its endpoints, rate limits and monthly price. A Consumer subscribes to it, and the subscription's status grants or removes access. Payment is left to a billing system, such as OBP-Stripe #### 1.2.6 Branch & ATM Services @@ -135,7 +137,7 @@ The Open Bank Project (OBP) is an open-source RESTful API platform for banks tha #### 1.2.7 Authentication & Authorization - **Multiple Auth Methods**: OAuth 2.0, OpenID Connect (OIDC) with multiple concurrent providers, Direct Login, Gateway Login, Sign-In With Ethereum -- **Consumer Management**: API consumer registration and key management, grant types, and Platform Apps (applications that act as themselves) +- **Consumer Management**: API consumer registration and key management, grant types, and Platform Apps (applications that act as themselves). Developers read their own Consumers, usage and subscriptions under `/my/consumers` without a Role - **Token Management**: Access token lifecycle management - **Consent Management**: PSD2-compliant consent workflows (AIS, PIS, PIIS) - **User Locks**: Account security with failed login attempt tracking @@ -150,6 +152,7 @@ The Open Bank Project (OBP) is an open-source RESTful API platform for banks tha - **Consumer Account Access** (v7.0.0): a view of an account granted to an application, so a service can act on the account as itself - **Entitlements and Scopes**: a person needs a Role as an Entitlement; a Platform App acting as itself needs it as a Scope - **Tenants** (v7.0.0): the customers of the operator of an OBP instance +- **Organisations** (v7.0.0): a team, such as a fintech, that owns Consumers together, so they stay with the team when someone leaves. Dynamic Entity records can be shared with an Organisation's members - **Mandates**: Corporate account governance with provisions, signatory panels, and multi-signature approval #### 1.2.9 Extensibility & Customization @@ -157,6 +160,7 @@ The Open Bank Project (OBP) is an open-source RESTful API platform for banks tha - **Spaces**: Dynamic Entities, Dynamic Resource Docs and Files live in a space: a bank, or `SYS` for the system space - **Dynamic Endpoints**: Create custom API endpoints without code deployment - **Dynamic Entities**: Define custom data models dynamically, with field-level read and write Roles, and a record of who created and last changed each record +- **Row-Level Access**: share single Dynamic Entity records with Users or with an Organisation's members, while holders of the entity's Get Role can still read every record - **Dynamic Entity Webhooks**: notify an outside system when records are created, updated or deleted - **Domain APIs**: publish a space's Dynamic Entities and Dynamic Resource Docs under a base path of their own, with their own OpenAPI document - **Dynamic Resource Documentation**: Custom endpoint documentation @@ -242,6 +246,7 @@ The Open Bank Project (OBP) is an open-source RESTful API platform for banks tha - **OBP Bank Node:** Runs inside a bank's network and connects its core banking system to an OBP instance run by a platform operator - **OBP Cohort:** Runs startup programmes, from the call for applications to graduation - **Conformator:** Tests open banking APIs against the agreed standard and issues signed conformance reports +- **OBP-Stripe:** Takes card payments for API Product Subscriptions through Stripe --- @@ -1436,6 +1441,7 @@ See the Glossary items OBP Bank Node, Connector and Adapter. - Public calls with application forms, saved drafts and eligibility checks - Reviews against a weighted rubric, with conflicts of interest declared first, and a ranked shortlist - Milestones, sessions, attendance and surveys for each startup, and stage gates before graduation +- Each startup is a team, an OBP Organisation, so every member sees the programme and the team answers each survey once - A Platform App in the OBP-Frontend repository (`apps/cohort`), keeping its records in OBP-API as Dynamic Entities See https://cohort.tesobe.com and the Glossary item OBP Cohort. @@ -1448,12 +1454,26 @@ See https://cohort.tesobe.com and the Glossary item OBP Cohort. - Requirements, and the tests that check them, kept in versioned suites; a suite can come from a standard OBP implements or from an OpenAPI document - Each participant has a space of its own and runs the suites against its own non-production systems +- Each participant has an OBP Organisation; its admins manage their own people, and Conformator keeps their Roles in the participant's space in line with its members - Participants submit results with evidence; reviewers assess them, and a separate approver decides - Approval issues a report signed with Ed25519, which anyone can check by its reference - Two Platform Apps in the OBP-Frontend repository: the web app (`apps/conformator`) and the runner that carries out the tests (`apps/conformator-runner`) See the Glossary item Conformator. +### 3.18 OBP-Stripe + +**Purpose:** Takes card payments for API Product Subscriptions through Stripe, and keeps each subscription's status in OBP-API in step with Stripe. + +**Key Features:** + +- OBP-API is the source of truth for prices: OBP-Stripe keeps a monthly Stripe Price for each API Product whose `BILLING_SYSTEM` attribute is `stripe` +- The Portal sends a developer to OBP-Stripe to pay. It checks that they may act for the Consumer, then starts a Stripe Checkout +- Stripe webhooks, and a check every 5 minutes, set the subscription to `active`, `past_due`, `suspended` or `cancelled`. OBP-API grants and removes access on each status; OBP-Stripe never grants a Role itself +- A Platform App written in Go, with its own token, ready for Docker and Kubernetes + +See the Glossary items OBP-Stripe and API Product Subscription. + --- ## 4. Standards Compliance @@ -1545,7 +1565,7 @@ POST /open-banking/v3.1/cbpii/funds-confirmation-consents - v4.0.0 (STABLE) - v5.0.0, v5.1.0 (STABLE) - v6.0.0 (DRAFT) - Mandates, Maker/Checker, gRPC connector, new User endpoints -- v7.0.0 (BLEEDING-EDGE) - Files, asset registry, Platform Apps, Consumer Account Access, Groups, Tenants, Domain APIs, Dynamic Entity webhooks, retention policies, Telemetry, utility payments and payment promises +- v7.0.0 (BLEEDING-EDGE) - Files, asset registry, Platform Apps, Consumer Account Access, Groups, Tenants, Organisations, API Product Subscriptions, Domain APIs, Dynamic Entity webhooks, retention policies, Telemetry, utility payments and payment promises **Key Endpoint Categories:** @@ -2770,6 +2790,15 @@ POST /obp/v5.1.0/management/consumers GET /obp/v5.1.0/management/consumers ``` +**Owners:** a Consumer is owned by the User who created it, or, once it is moved into an Organisation, by the Organisation's members together. Owners need no Role to read their Consumers, their usage, Scopes and API Product Subscriptions: + +```bash +GET /obp/v7.0.0/my/consumers # the Consumers you own, yours and your Organisations' +GET /obp/v7.0.0/my/consumers/CONSUMER_ID/usage +PUT /obp/v7.0.0/my/consumers/CONSUMER_ID/organisation # move it into an Organisation you are an admin of +POST /obp/v7.0.0/my/organisations # create an Organisation; you become its admin +``` + **Grant types:** a Consumer's grant types control how tokens can be obtained through it: whether people can log in through it, whether the application can get a token for itself (`client_credentials`), or both. A Consumer with no grant types set can be used in every way. Grant types do not decide what the application may do with a token. **Platform Apps:** a Platform App is an application the installation runs as part of its own deployment, such as the Portal, API Manager, Opey, Sentinel, Cohort, Conformator or a Bank Node. Only a Platform App can act as itself on its Consumer's Scopes (see 8.7). @@ -2788,7 +2817,7 @@ POST /obp/v7.0.0/consumers/CONSUMER_ID/scopes # grant a Scope OPERATORS: mark every application that acts as itself as a Platform App. Without the mark, a Consumer's Scopes only work as a limit on people. -See the Glossary items Platform Apps, Consumer Grant Types and API.Entitlements and Scopes. +See the Glossary items Consumer, Organisation, Platform Apps, Consumer Grant Types and API.Entitlements and Scopes. ### 7.4 Mutual TLS and PSD2 Certificates @@ -2837,6 +2866,7 @@ Roles that let a holder act at any bank (`...AtAnyBank`) are being retired in fa | `CanCreateCustomer` | Create customers | Bank | | `CanCreateBranch` | Create branch records | Bank | | `CanCreateEntitlementAtOneBank` | Grant Roles at one bank | Bank | +| `CanDeleteEntitlementAtOneBank` | Remove Roles at one bank | Bank | | `CanGetAnyUser` | View any user details | System | | `CanReadMetrics` | View API metrics | System | | `CanCreateConsumer` | Create Consumers | System | @@ -3960,6 +3990,33 @@ POST /obp/v7.0.0/banks/BANK_ID/open-corridor/fee-settlements The caller is a User with access to the view, or an application acting as itself whose Consumer has been given access to the view (Consumer Account Access, section 8.3). +#### Workflow 7: A Team Subscribes to an API Product (v7.0.0) + +A fintech's developers work as a team. They put their application in an Organisation, then subscribe it to an API Product. No Role is needed for any of these calls. + +```bash +# 1. Create the team; the caller becomes its admin +POST /obp/v7.0.0/my/organisations +{ "name": "Example Pay" } + +# 2. Add a colleague by their user_id +POST /obp/v7.0.0/my/organisations/ORGANISATION_ID/members +{ "user_id": "USER_ID", "member_role": "member" } + +# 3. Move the application into the team +PUT /obp/v7.0.0/my/consumers/CONSUMER_ID/organisation +{ "organisation_id": "ORGANISATION_ID" } + +# 4. Subscribe it to an API Product +POST /obp/v7.0.0/banks/BANK_ID/api-products/API_PRODUCT_CODE/subscriptions +{ "consumer_id": "CONSUMER_ID" } + +# 5. Any member reads the team's subscriptions +GET /obp/v7.0.0/my/api-product-subscriptions +``` + +The subscription starts as `requested`, unless the product's `BILLING_SYSTEM` attribute is `none`, which activates it at once. When it becomes `active`, OBP-API gives the Consumer the product's rate limits and Scopes. If the product is paid for by card, the Portal sends the developer to OBP-Stripe to pay. See the Glossary items Organisation and API Product Subscription. + --- ## 12. Deployment Workflows diff --git a/obp-api/src/main/scala/bootstrap/liftweb/Boot.scala b/obp-api/src/main/scala/bootstrap/liftweb/Boot.scala index b7e11aae4e..b43cee8007 100644 --- a/obp-api/src/main/scala/bootstrap/liftweb/Boot.scala +++ b/obp-api/src/main/scala/bootstrap/liftweb/Boot.scala @@ -1059,6 +1059,7 @@ object ToSchemify extends MdcLoggable { DynamicEntity, DynamicData, DynamicDataAccess, + code.DynamicData.DynamicDataOrganisationAccess, code.api.dynamic.entity.projection.DynamicEntityIndex, // Files: written in full because Boot imports java.io.File. code.files.File, @@ -1151,6 +1152,8 @@ object ToSchemify extends MdcLoggable { Group, code.group.GroupMembership, Tenant, + code.organisation.Organisation, + code.organisation.OrganisationMember, code.model.dataAccess.SelfServiceBank, RoutingScheme, BankSupportedRoutingScheme, diff --git a/obp-api/src/main/scala/code/api/dynamic/entity/Http4sDynamicEntity.scala b/obp-api/src/main/scala/code/api/dynamic/entity/Http4sDynamicEntity.scala index a170a55aab..58cb2e6468 100644 --- a/obp-api/src/main/scala/code/api/dynamic/entity/Http4sDynamicEntity.scala +++ b/obp-api/src/main/scala/code/api/dynamic/entity/Http4sDynamicEntity.scala @@ -29,7 +29,7 @@ import cats.data.{Kleisli, OptionT} import cats.effect.IO import code.DynamicData.{DynamicData, DynamicDataProvider, DynamicDataAccessProvider, DynamicDataAccessPermission, DynamicDataT} import code.api.Constant.PARAM_LOCALE -import code.api.dynamic.entity.helper.{CommunityEntityName, DynamicEntityHelper, DynamicEntityInfo, DynamicEntitySpace, EntityAccessName, EntityName, PublicEntityName} +import code.api.dynamic.entity.helper.{CommunityEntityName, DynamicEntityHelper, DynamicEntityInfo, DynamicEntitySpace, EntityAccessName, EntityName, EntityOrganisationAccessName, PublicEntityName} import code.api.dynamic.entity.query.{FieldSpec, InMemoryQueryExecutor, JoinTargetInfo, QueryParamParser, QueryPlan, QueryPlanner} import code.api.dynamic.entity.projection.{IndexingCapabilities, PostgresProjectionBackend, ProjectionReadiness} import cats.effect.unsafe.implicits.{global => ioRuntime} // aliased: avoids clashing with the EC `global` imported below @@ -595,8 +595,19 @@ object Http4sDynamicEntity extends MdcLoggable { ("can_grant" -> a.canGrant) ~ ("granted_by" -> a.grantedBy) + private def organisationAccessRowJson(a: code.DynamicData.DynamicDataOrganisationAccessT): JObject = + ("organisation_id" -> a.organisationId) ~ + ("can_read" -> a.canRead) ~ + ("can_update" -> a.canUpdate) ~ + ("can_delete" -> a.canDelete) ~ + ("can_grant" -> a.canGrant) ~ + ("granted_by" -> a.grantedBy) + + // Grants to Users are listed under "access" and grants to Organisations under "organisation_access", + // so a client that reads user_id from every "access" entry keeps working. private def rowAccessListJson(bankId: Option[String], entityName: String, dataId: String): JObject = - ("access" -> JArray(aclVend.getAccessForRow(bankId, entityName, dataId).map(rowAccessRowJson))) + ("access" -> JArray(aclVend.getAccessForRow(bankId, entityName, dataId).map(rowAccessRowJson))) ~ + ("organisation_access" -> JArray(aclVend.getOrganisationAccessForRow(bankId, entityName, dataId).map(organisationAccessRowJson))) // Shared preamble: before-intercept, auth, bank, flag-off (400), grant authorisation (403). private def rowAccessAuthorise(cc: CallContext, bankId: Option[String], entityName: String, id: String, @@ -632,16 +643,34 @@ object Http4sDynamicEntity extends MdcLoggable { case o: JObject => List(o) case _ => Nil } - _ <- Helper.booleanToFuture(s"$InvalidJsonFormat each access entry needs a non-empty user_id", 400, cc = callContext) { - entries.nonEmpty && entries.forall(o => strField(o, "user_id").isDefined) + _ <- Helper.booleanToFuture(InvalidRecordAccessEntry, 400, cc = callContext) { + entries.nonEmpty && entries.forall(o => strField(o, "user_id").isDefined != strField(o, "organisation_id").isDefined) + } + unknownOrganisationIds = entries.flatMap(o => strField(o, "organisation_id")) + .filterNot(organisationId => code.organisation.Organisations.getOrganisation(organisationId).isDefined) + _ <- Helper.booleanToFuture(s"$RecordAccessOrganisationNotFound Current value: ${unknownOrganisationIds.mkString(", ")}", 404, cc = callContext) { + unknownOrganisationIds.isEmpty } _ = entries.foreach { o => - aclVend.grant(bankId, entityName, id, strField(o, "user_id").get, - canRead = boolField(o, "can_read", default = false), - canUpdate = boolField(o, "can_update", default = false), - canDelete = boolField(o, "can_delete", default = false), - canGrant = boolField(o, "can_grant", default = true), // §8.1: re-share by default - grantedBy = granter.userId) + (strField(o, "user_id"), strField(o, "organisation_id")) match { + case (Some(grantUserId), _) => + aclVend.grant(bankId, entityName, id, grantUserId, + canRead = boolField(o, "can_read", default = false), + canUpdate = boolField(o, "can_update", default = false), + canDelete = boolField(o, "can_delete", default = false), + canGrant = boolField(o, "can_grant", default = true), // §8.1: re-share by default + grantedBy = granter.userId) + case (None, Some(grantOrganisationId)) => + // can_grant defaults to false here: with it, every member could change the access list, + // including removing the person who shared the record. + aclVend.grantToOrganisation(bankId, entityName, id, grantOrganisationId, + canRead = boolField(o, "can_read", default = false), + canUpdate = boolField(o, "can_update", default = false), + canDelete = boolField(o, "can_delete", default = false), + canGrant = boolField(o, "can_grant", default = false), + grantedBy = granter.userId) + case _ => + } } } yield rowAccessListJson(bankId, entityName, id) } @@ -654,6 +683,14 @@ object Http4sDynamicEntity extends MdcLoggable { } yield (("revoked_count" -> removed): JObject) } + private def revokeOrganisationRowAccess(req: Request[IO], bankId: Option[String], entityName: String, id: String, grantOrganisationId: String): IO[Response[IO]] = + EndpointHelpers.executeAndRespond(req) { cc => + for { + _ <- rowAccessAuthorise(cc, bankId, entityName, id, DELETE) + removed = aclVend.revokeOrganisation(bankId, entityName, id, grantOrganisationId).getOrElse(0) + } yield (("revoked_count" -> removed): JObject) + } + // ----- generic endpoint (authenticated, system / bank / personal) ----- private def genericGet(req: Request[IO], bankId: Option[String], entityName: String, id: String, isPersonalEntity: Boolean): IO[Response[IO]] = @@ -917,6 +954,8 @@ object Http4sDynamicEntity extends MdcLoggable { Some(r => upsertRowAccess(r, bankId, entityName, id)) case (Method.DELETE, EntityAccessName(bankId, entityName, id, Some(grantUserId))) => Some(r => revokeRowAccess(r, bankId, entityName, id, grantUserId)) + case (Method.DELETE, EntityOrganisationAccessName(bankId, entityName, id, grantOrganisationId)) => + Some(r => revokeOrganisationRowAccess(r, bankId, entityName, id, grantOrganisationId)) case (method, EntityName(bankId, entityName, id, isPersonalEntity)) => method match { case Method.GET => Some(r => genericGet(r, bankId, entityName, id, isPersonalEntity)) diff --git a/obp-api/src/main/scala/code/api/dynamic/entity/helper/DynamicEntityHelper.scala b/obp-api/src/main/scala/code/api/dynamic/entity/helper/DynamicEntityHelper.scala index 7710e6ca8a..d3ed362cf7 100644 --- a/obp-api/src/main/scala/code/api/dynamic/entity/helper/DynamicEntityHelper.scala +++ b/obp-api/src/main/scala/code/api/dynamic/entity/helper/DynamicEntityHelper.scala @@ -31,7 +31,7 @@ import code.api.Constant import code.api.util.APIUtil.{EmptyBody, ResourceDoc, userAuthenticationMessage} import code.api.util.ApiRole.getOrCreateDynamicApiRole import code.api.util.ApiTag._ -import code.api.util.ErrorMessages.{InvalidJsonFormat, UnknownError, UserHasMissingRoles, AuthenticatedUserIsRequired, ConsentMyResourcesMissing} +import code.api.util.ErrorMessages.{InvalidJsonFormat, UnknownError, UserHasMissingRoles, AuthenticatedUserIsRequired, ConsentMyResourcesMissing, InvalidRecordAccessEntry, RecordAccessOrganisationNotFound} import code.api.util._ import com.openbankproject.commons.model.enums.{DynamicEntityFieldType, DynamicEntityOperation} import com.openbankproject.commons.util.{ApiVersion, ScannedApiVersion} @@ -146,6 +146,18 @@ object EntityAccessName { } } +object EntityOrganisationAccessName { + def unapply(url: List[String]): Option[(Option[String], String, String, String)] = url match { + case SpaceSegments(space, rest) => rest match { + //eg: /FooBar21/FOO_BAR21_ID/access/organisations/ORGANISATION_ID (with or without the bank segment) + case entityName :: id :: "access" :: "organisations" :: organisationId :: Nil if DefinitionIn(space, entityName) => + Some((space, entityName, id, organisationId)) + case _ => None + } + case _ => None + } +} + object DynamicEntityHelper { /** @@ -936,13 +948,21 @@ object DynamicEntityHelper { ("can_delete" -> false) ~ ("can_grant" -> true) val accessGrantedByExample: JObject = ("granted_by" -> ExampleValue.userIdExample.value) + val organisationAccessEntryExample: JObject = + ("organisation_id" -> ExampleValue.organisationIdExample.value) ~ + ("can_read" -> true) ~ + ("can_update" -> true) ~ + ("can_delete" -> false) ~ + ("can_grant" -> false) val accessListExample: JObject = - ("access" -> JArray(List(accessEntryExample merge accessGrantedByExample))) + ("access" -> JArray(List(accessEntryExample merge accessGrantedByExample))) ~ + ("organisation_access" -> JArray(List(organisationAccessEntryExample merge accessGrantedByExample))) val accessRoleNote = s"""This endpoint exists because $splitName is defined with `useRowLevelAccess`: a per-record access list decides |read, update, delete and grant in place of the entity's Get, Update and Delete roles. | - |The caller must hold `can_grant` on this record — the User who created it does — or the + |The caller must hold `can_grant` on this record — the User who created it does, and so do the members of an + |Organisation granted it — or the |`${dynamicEntityInfo.canGrantRowAccessRole.toString()}` role, which administers the access list of any record. |""".stripMargin @@ -976,11 +996,18 @@ object DynamicEntityHelper { "PUT", s"$accessResourceDocUrl", s"Grant Access to a $splitName Record", - s"""Grant (or update) another User's access to one $splitName record. + s"""Grant (or update) another User's or an Organisation's access to one $splitName record. + | + |The body is one entry or an array of entries. Each entry names either a `user_id` or an `organisation_id`. + |`can_read`, `can_update` and `can_delete` default to `false`. + | + |For a User, `can_grant` defaults to `true`, so a grantee may share the record further by default. | - |The body is one entry or an array of entries. `user_id` is required; `can_read`, `can_update` and - |`can_delete` default to `false` and `can_grant` defaults to `true`, so a grantee may re-share by default. - |Sending an entry for a User who already holds access replaces their permissions. + |For an Organisation, `can_grant` defaults to `false`. The grant applies to every member of the Organisation + |while it is active. People who join the Organisation later get access, and people who leave lose it. + |A suspended Organisation grants nothing. + | + |Sending an entry for a User or Organisation that already holds access replaces their permissions. | |$accessRoleNote | @@ -992,6 +1019,8 @@ object DynamicEntityHelper { AuthenticatedUserIsRequired, UserHasMissingRoles, InvalidJsonFormat, + InvalidRecordAccessEntry, + RecordAccessOrganisationNotFound, UnknownError ), List(apiTag, apiTagDynamicEntity, apiTagDynamic), @@ -1025,6 +1054,33 @@ object DynamicEntityHelper { Some(List(dynamicEntityInfo.canGrantRowAccessRole)), createdByBankId= dynamicEntityInfo.bankId ) + + resourceDocs += (DynamicEntityOperation.DELETE, s"AccessOrganisation$splitNameWithBankId") -> ResourceDoc( + apiVersion, + buildRevokeOrganisationRowAccessFunctionName(bankId, entityName), + "DELETE", + s"$accessResourceDocUrl/organisations/ORGANISATION_ID", + s"Revoke an Organisation's Access to a $splitName Record", + s"""Revoke an Organisation's access to one $splitName record. Its members lose the access the grant gave them. + | + |Grants that members made to other Users stay. Each of those was made by one person, and revoking that + |person removes them. + | + |$accessRoleNote + | + |${userAuthenticationMessage(true)} + |""".stripMargin, + EmptyBody, + ("revoked_count" -> 1): JObject, + List( + AuthenticatedUserIsRequired, + UserHasMissingRoles, + UnknownError + ), + List(apiTag, apiTagDynamicEntity, apiTagDynamic), + Some(List(dynamicEntityInfo.canGrantRowAccessRole)), + createdByBankId= dynamicEntityInfo.bankId + ) } resourceDocs @@ -1039,6 +1095,7 @@ object DynamicEntityHelper { private def buildGetRowAccessFunctionName(bankId:Option[String], entityName: String) = s"dynamicEntity_get${entityName}RowAccess_${bankId.getOrElse("")}" private def buildGrantRowAccessFunctionName(bankId:Option[String], entityName: String) = s"dynamicEntity_grant${entityName}RowAccess_${bankId.getOrElse("")}" private def buildRevokeRowAccessFunctionName(bankId:Option[String], entityName: String) = s"dynamicEntity_revoke${entityName}RowAccess_${bankId.getOrElse("")}" + private def buildRevokeOrganisationRowAccessFunctionName(bankId:Option[String], entityName: String) = s"dynamicEntity_revoke${entityName}OrganisationRowAccess_${bankId.getOrElse("")}" @inline private def buildOperationId(bankId:Option[String], entityName: String, fun: (Option[String], String) => String): String = { diff --git a/obp-api/src/main/scala/code/api/dynamic/entity/projection/PostgresProjectionBackend.scala b/obp-api/src/main/scala/code/api/dynamic/entity/projection/PostgresProjectionBackend.scala index 90eb5a29fe..50a3278d60 100644 --- a/obp-api/src/main/scala/code/api/dynamic/entity/projection/PostgresProjectionBackend.scala +++ b/obp-api/src/main/scala/code/api/dynamic/entity/projection/PostgresProjectionBackend.scala @@ -159,10 +159,20 @@ object PostgresProjectionBackend extends DynamicEntityQueryBackend { (isRowLevel, callerUserId) match { case (true, None) => fr"AND FALSE" case (true, Some(uid)) => - fr"AND EXISTS (SELECT 1 FROM" ++ Fragment.const(s"${ProjectionStore.aclTable} acl") ++ - fr"WHERE" ++ Fragment.const(s"acl.${ProjectionStore.aclDataIdColumn} = $childBlobAlias.${ProjectionStore.idColumn}") ++ - fr"AND" ++ Fragment.const(s"acl.${ProjectionStore.aclUserIdColumn}") ++ fr"=" ++ fr"$uid" ++ - fr"AND" ++ Fragment.const(s"acl.${ProjectionStore.aclCanReadColumn} = true") ++ fr")" + import ProjectionStore._ + val activeStatus = code.organisation.Organisations.StatusActive + fr"AND (EXISTS (SELECT 1 FROM" ++ Fragment.const(s"$aclTable acl") ++ + fr"WHERE" ++ Fragment.const(s"acl.$aclDataIdColumn = $childBlobAlias.$idColumn") ++ + fr"AND" ++ Fragment.const(s"acl.$aclUserIdColumn") ++ fr"=" ++ fr"$uid" ++ + fr"AND" ++ Fragment.const(s"acl.$aclCanReadColumn = true") ++ fr")" ++ + // or a grant to an active Organisation the caller is a member of + fr"OR EXISTS (SELECT 1 FROM" ++ Fragment.const(s"$organisationAclTable oacl") ++ + Fragment.const(s"JOIN $organisationMemberTable om ON om.$organisationMemberOrgIdColumn = oacl.$organisationAclOrgIdColumn") ++ + Fragment.const(s"JOIN $organisationTable org ON org.$organisationIdColumn = oacl.$organisationAclOrgIdColumn") ++ + fr"WHERE" ++ Fragment.const(s"oacl.$organisationAclDataIdColumn = $childBlobAlias.$idColumn") ++ + fr"AND" ++ Fragment.const(s"om.$organisationMemberUserIdColumn") ++ fr"=" ++ fr"$uid" ++ + fr"AND" ++ Fragment.const(s"org.$organisationStatusColumn") ++ fr"=" ++ fr"$activeStatus" ++ + fr"AND" ++ Fragment.const(s"oacl.$organisationAclCanReadColumn = true") ++ fr"))" case _ => Fragment.empty } } diff --git a/obp-api/src/main/scala/code/api/dynamic/entity/projection/ProjectionStore.scala b/obp-api/src/main/scala/code/api/dynamic/entity/projection/ProjectionStore.scala index c2df5157b2..0836a416d4 100644 --- a/obp-api/src/main/scala/code/api/dynamic/entity/projection/ProjectionStore.scala +++ b/obp-api/src/main/scala/code/api/dynamic/entity/projection/ProjectionStore.scala @@ -59,6 +59,19 @@ object ProjectionStore { val aclUserIdColumn: String = code.DynamicData.DynamicDataAccess.UserId.dbColumnName val aclCanReadColumn: String = code.DynamicData.DynamicDataAccess.CanRead.dbColumnName + // Grants to Organisations, and the membership tables they are checked against: a join onto a row-level + // child also counts child rows granted to an active Organisation the caller belongs to. + val organisationAclTable: String = code.DynamicData.DynamicDataOrganisationAccess.dbTableName + val organisationAclDataIdColumn: String = code.DynamicData.DynamicDataOrganisationAccess.DynamicDataId.dbColumnName + val organisationAclOrgIdColumn: String = code.DynamicData.DynamicDataOrganisationAccess.OrganisationId.dbColumnName + val organisationAclCanReadColumn: String = code.DynamicData.DynamicDataOrganisationAccess.CanRead.dbColumnName + val organisationTable: String = code.organisation.Organisation.dbTableName + val organisationIdColumn: String = code.organisation.Organisation.OrganisationId.dbColumnName + val organisationStatusColumn: String = code.organisation.Organisation.Status.dbColumnName + val organisationMemberTable: String = code.organisation.OrganisationMember.dbTableName + val organisationMemberOrgIdColumn: String = code.organisation.OrganisationMember.OrganisationId.dbColumnName + val organisationMemberUserIdColumn: String = code.organisation.OrganisationMember.UserId.dbColumnName + /** One indexed field's value for a record: safe column, SQL type, coerced text (None => NULL). */ case class ColumnValue(safeColumn: String, sqlType: String, value: Option[String]) diff --git a/obp-api/src/main/scala/code/api/util/ApiRole.scala b/obp-api/src/main/scala/code/api/util/ApiRole.scala index e814964803..83c1911810 100644 --- a/obp-api/src/main/scala/code/api/util/ApiRole.scala +++ b/obp-api/src/main/scala/code/api/util/ApiRole.scala @@ -1580,6 +1580,15 @@ object ApiRole extends MdcLoggable{ case class CanGetGroupsAtOneBank(requiresBankId: Boolean = true) extends ApiRole lazy val canGetGroupsAtOneBank = CanGetGroupsAtOneBank() + // Organisation roles for staff, held at the Organisation's bank_id: the bank that administers it, or SYS. + // Not CanCreateOrganisation, CanGetOrganisation or CanUpdateOrganisation: the Tenant migration renames those. + case class CanCreateOrganisationAtOneBank(requiresBankId: Boolean = true) extends ApiRole + lazy val canCreateOrganisationAtOneBank = CanCreateOrganisationAtOneBank() + case class CanGetOrganisationAtOneBank(requiresBankId: Boolean = true) extends ApiRole + lazy val canGetOrganisationAtOneBank = CanGetOrganisationAtOneBank() + case class CanUpdateOrganisationStatusAtOneBank(requiresBankId: Boolean = true) extends ApiRole + lazy val canUpdateOrganisationStatusAtOneBank = CanUpdateOrganisationStatusAtOneBank() + // Tenant management roles. A Tenant belongs to no bank, so these are system Roles. case class CanCreateTenant(requiresBankId: Boolean = false) extends ApiRole lazy val canCreateTenant = CanCreateTenant() diff --git a/obp-api/src/main/scala/code/api/util/ApiTag.scala b/obp-api/src/main/scala/code/api/util/ApiTag.scala index 084d8d4f8e..93de46e1f3 100644 --- a/obp-api/src/main/scala/code/api/util/ApiTag.scala +++ b/obp-api/src/main/scala/code/api/util/ApiTag.scala @@ -121,6 +121,7 @@ object ApiTag { val apiTagChat = ResourceDocTag("Chat") val apiTagGroup = ResourceDocTag("Group") val apiTagTenant = ResourceDocTag("Tenant") + val apiTagOrganisation = ResourceDocTag("Organisation") val apiTagRoutingScheme = ResourceDocTag("Routing-Scheme") val apiTagPayee = ResourceDocTag("Payee") val apiTagWebhook = ResourceDocTag("Webhook") diff --git a/obp-api/src/main/scala/code/api/util/ErrorMessages.scala b/obp-api/src/main/scala/code/api/util/ErrorMessages.scala index 1cf758a5b3..327e4e7435 100644 --- a/obp-api/src/main/scala/code/api/util/ErrorMessages.scala +++ b/obp-api/src/main/scala/code/api/util/ErrorMessages.scala @@ -545,6 +545,7 @@ object ErrorMessages { val BankAccountNotFoundByAccountRouting = "OBP-30073: Bank Account not found. Please specify valid values for account routing scheme and address." val BankAccountNotFoundByIban = "OBP-30074: Bank Account not found. Please specify a valid value for iban." val AccountRoutingNotFound = "OBP-30075: Account routing not found, Please specify valid values for account routing scheme and address" + val InvalidAccountRoutingAddressRegex = "OBP-30649: Invalid account_routing.address. It must be a valid regular expression." val AccountRoutingNotUnique = "OBP-31075: Routing is not unique at this instance" val BankAccountNotFoundByAccountId = "OBP-30076: Bank Account not found. Please specify a valid value for ACCOUNT_ID." @@ -572,7 +573,7 @@ object ErrorMessages { val ApiProductSubscriptionAlreadyExists = "OBP-30561: ApiProductSubscription already exists. The Consumer already holds a non-cancelled subscription to this API Product." val InvalidApiProductSubscriptionStatus = "OBP-30562: Invalid ApiProductSubscription status. Allowed values are: requested, active, past_due, suspended, cancelled." val InvalidApiProductSubscriptionStatusTransition = "OBP-30563: Invalid ApiProductSubscription status transition." - val ConsumerNotOwnedByUser = "OBP-30564: The Consumer was not created by the current User. Please specify the CONSUMER_ID of one of your own Consumers." + val ConsumerNotOwnedByUser = "OBP-30564: The Consumer is not yours. Please specify the CONSUMER_ID of a Consumer you created, or of one that belongs to your Organisation." val CreateApiProductSubscriptionError = "OBP-30565: Could not create ApiProductSubscription." val UpdateApiProductSubscriptionError = "OBP-30566: Could not update ApiProductSubscription." val DeleteApiProductSubscriptionError = "OBP-30567: Could not delete ApiProductSubscription." @@ -636,6 +637,27 @@ object ErrorMessages { val UpdateTenantError = "OBP-30512: Could not update Tenant." val DeleteTenantError = "OBP-30513: Could not delete Tenant." + // Organisations: a group of people that owns Consumers (OBP-30630 .. OBP-30645) + val OrganisationNotFound = "OBP-30630: Organisation not found. Please specify the ORGANISATION_ID of an Organisation you belong to." + val OrganisationAdminRequired = "OBP-30631: Only an admin of the Organisation can do this." + val InvalidOrganisationMemberRole = "OBP-30632: Invalid member_role. Allowed values are: admin, member." + val OrganisationMemberAlreadyExists = "OBP-30633: The User is already a member of this Organisation." + val OrganisationMemberNotFound = "OBP-30634: The User is not a member of this Organisation." + val OrganisationNeedsAnAdmin = "OBP-30635: An Organisation must keep at least one admin. Make another member an admin first." + val OrganisationHasConsumers = "OBP-30636: The Organisation still has Consumers. Move them out of it first." + val InvalidOrganisationStatus = "OBP-30637: Invalid Organisation status. Allowed values are: active, suspended." + val InvalidOrganisationName = "OBP-30638: The name of an Organisation must be 1 to 255 characters." + val CreateOrganisationError = "OBP-30639: Could not create the Organisation." + val UpdateOrganisationError = "OBP-30640: Could not update the Organisation." + val DeleteOrganisationError = "OBP-30641: Could not delete the Organisation." + val UpdateOrganisationMemberError = "OBP-30642: Could not change the members of the Organisation." + val MyConsumerNotFound = "OBP-30643: Consumer not found. Please specify the CONSUMER_ID of a Consumer you created or one that belongs to your Organisation." + val UpdateConsumerOrganisationError = "OBP-30644: Could not change the Organisation of the Consumer." + val InvalidOrganisationBankId = "OBP-30645: Invalid bank_id for an Organisation. Use SYS, or the BANK_ID of a bank that exists." + val RecordAccessOrganisationNotFound = "OBP-30646: Organisation not found. Please specify the ORGANISATION_ID of an Organisation that exists." + val MyOrganisationBankIdNotAllowed = "OBP-30648: An Organisation you create for yourself is always at SYS, so leave out bank_id. To create an Organisation at a bank, use POST /management/organisations with CanCreateOrganisationAtOneBank at that bank." + val InvalidRecordAccessEntry = "OBP-30647: Invalid access entry. Each entry needs either a user_id or an organisation_id, not both." + // Data retention (OBP-30582 .. OBP-30596) val RetentionPolicyNotFound = "OBP-30609: Retention policy not found in this space. Please specify a valid value for RETENTION_POLICY_ID." val InvalidRetentionPolicy = "OBP-30610: Invalid retention policy. " @@ -1372,12 +1394,14 @@ object ErrorMessages { import scala.meta._ val source: Source = new java.io.File("src/main/scala/code/api/util/ErrorMessages.scala").parse[Source].get + // A message may be a plain string ("OBP-..."), an interpolated one (s"OBP-...") or a triple-quoted one + // ("""OBP-..."""). All three are checked; the number is the OBP-NNNNN at the start, without its quotes. + val messageNumberAtStart = """^s?(?:"{3}|")(OBP-[0-9]+)""".r val listOfMessaegeNumbers = source.collect { case obj: Defn.Object if obj.name.value == "ErrorMessages" => obj.collect { - case v: Defn.Val if v.rhs.syntax.startsWith(""""OBP-""") => - val messageNumber = v.rhs.syntax.split(":") - messageNumber(0) + case v: Defn.Val if messageNumberAtStart.findFirstMatchIn(v.rhs.syntax).isDefined => + "\"" + messageNumberAtStart.findFirstMatchIn(v.rhs.syntax).get.group(1) } } val list = listOfMessaegeNumbers.flatten diff --git a/obp-api/src/main/scala/code/api/util/ExampleValue.scala b/obp-api/src/main/scala/code/api/util/ExampleValue.scala index 5d4af8c6c4..f150c5608b 100644 --- a/obp-api/src/main/scala/code/api/util/ExampleValue.scala +++ b/obp-api/src/main/scala/code/api/util/ExampleValue.scala @@ -76,6 +76,7 @@ object ExampleValue { lazy val userIdExample = ConnectorField("9ca9a7e4-6d02-40e3-a129-0b2bf89de9b1", s"A string that MUST uniquely identify the user on this OBP instance.") glossaryItems += makeGlossaryItem("User.userId", userIdExample) + lazy val organisationIdExample = ConnectorField("8ca8a7e4-6d02-48e3-a029-0b2bf89de9f0", s"A string that MUST uniquely identify the Organisation (a team that owns Consumers) on this OBP instance.") lazy val relationshipTypeExample = ConnectorField("Owner", s"Relationship between two parties.") glossaryItems += makeGlossaryItem("Customer.relationshipType", relationshipTypeExample) diff --git a/obp-api/src/main/scala/code/api/util/Glossary.scala b/obp-api/src/main/scala/code/api/util/Glossary.scala index 6934c6df0a..81a2ce0854 100644 --- a/obp-api/src/main/scala/code/api/util/Glossary.scala +++ b/obp-api/src/main/scala/code/api/util/Glossary.scala @@ -1579,7 +1579,11 @@ object Glossary extends MdcLoggable { | |A Scope lets an application call an endpoint. A Platform App that acts on an account as itself also needs access to a view of that account. An example is initiating payments from the account. See ${getGlossaryItemLink("Consumer Account Access")}. | - |## Switching a Consumer off + |## Who owns a Consumer +| +|A Consumer is owned by the User who created it. It can be moved into an ${getGlossaryItemLink("Organisation")}, and then its members own it together, so it stays with the team when someone leaves. Owners need no Role to read their Consumers, their usage, Scopes and API Product Subscriptions under `/my/consumers`, or to subscribe them to API Products. See ${getGlossaryItemLink("API Product Subscription")}. +| +|## Switching a Consumer off | |An administrator can disable a Consumer. Every call through it is then refused, by people and by the application itself. It can be enabled again later. | @@ -1592,6 +1596,7 @@ object Glossary extends MdcLoggable { |- [Update Consumer Certificate](${apiExplorerUrl}/resource-docs/OBPv7.0.0?operationid=OBPv7.0.0-updateConsumerCertificate): `PUT /obp/v7.0.0/management/consumers/CONSUMER_ID/consumer/certificate` |- [Update Consumer RedirectURL](${apiExplorerUrl}/resource-docs/OBPv7.0.0?operationid=OBPv7.0.0-updateConsumerRedirectURL): `PUT /obp/v7.0.0/management/consumers/CONSUMER_ID/consumer/redirect_url` |- [Get Current Consumer](${apiExplorerUrl}/resource-docs/OBPv6.0.0?operationid=OBPv6.0.0-getCurrentConsumer): `GET /obp/v6.0.0/consumers/current`, for an application to read its own Consumer. +|- [Get My Consumers](${apiExplorerUrl}/resource-docs/OBPv7.0.0?operationid=OBPv7.0.0-getMyConsumers): `GET /obp/v7.0.0/my/consumers`, for owners to read their Consumers. | |The endpoints for grant types, Scopes, Platform Apps and account access are listed in their own items. |""".stripMargin) @@ -3693,9 +3698,19 @@ object Glossary extends MdcLoggable { | |Only the rate limit record and the Scopes created by the subscription are touched. Limits and Scopes granted by hand are never removed. Overlapping rate limit records are summed, so a Consumer holding two products gets both allowances. | -|A developer never needs a Role to subscribe their own Consumer, read their own subscriptions or cancel them. Roles exist for bank staff (enrol a partner's Consumer, approve, suspend, reinstate) and for billing systems (move the status on payment events). Two attributes on the API Product decide the flow: `SELF_SUBSCRIBE` (may developers subscribe their own Consumers; default `true`) and `BILLING_SYSTEM` (`none` activates at once; `manual` waits for a bank admin; `stripe` or `invoice_ninja` waits for that billing system). +|Anyone who may act for a Consumer needs no Role to subscribe it, read its subscriptions or cancel them. That is the User who created it, or, once it belongs to an ${getGlossaryItemLink("Organisation")}, every member of that Organisation. Roles exist for bank staff (enrol a partner's Consumer, approve, suspend, reinstate) and for billing systems (move the status on payment events). Two attributes on the API Product decide the flow: `SELF_SUBSCRIBE` (may developers subscribe their own Consumers; default `true`) and `BILLING_SYSTEM` (`none` activates at once; `manual` waits for a bank admin; `stripe` or `invoice_ninja` waits for that billing system). +| +|OBP-API core carries no billing vocabulary: payments, invoices and refunds live in the billing system, which only ever changes the subscription status. For `stripe`, that billing system is ${getGlossaryItemLink("OBP-Stripe")}. | -|OBP-API core carries no billing vocabulary: payments, invoices and refunds live in the billing system, which only ever changes the subscription status. +|## Endpoints +| +|- [Create Api Product Subscription](${apiExplorerUrl}/resource-docs/OBPv7.0.0?operationid=OBPv7.0.0-createApiProductSubscription): `POST /obp/v7.0.0/banks/BANK_ID/api-products/API_PRODUCT_CODE/subscriptions` +|- [Get My Api Product Subscriptions](${apiExplorerUrl}/resource-docs/OBPv7.0.0?operationid=OBPv7.0.0-getMyApiProductSubscriptions): `GET /obp/v7.0.0/my/api-product-subscriptions` +|- [Cancel My Api Product Subscription](${apiExplorerUrl}/resource-docs/OBPv7.0.0?operationid=OBPv7.0.0-updateMyApiProductSubscriptionStatus): `PUT /obp/v7.0.0/my/api-product-subscriptions/API_PRODUCT_SUBSCRIPTION_ID/status` +|- [Get My Consumer Api Product Subscriptions](${apiExplorerUrl}/resource-docs/OBPv7.0.0?operationid=OBPv7.0.0-getMyConsumerApiProductSubscriptions): `GET /obp/v7.0.0/my/consumers/CONSUMER_ID/api-product-subscriptions` +|- [Get Api Product Subscriptions by Product](${apiExplorerUrl}/resource-docs/OBPv7.0.0?operationid=OBPv7.0.0-getApiProductSubscriptionsByProduct): `GET /obp/v7.0.0/banks/BANK_ID/api-products/API_PRODUCT_CODE/subscriptions` +|- [Update Api Product Subscription Status](${apiExplorerUrl}/resource-docs/OBPv7.0.0?operationid=OBPv7.0.0-updateApiProductSubscriptionStatus): `PUT /obp/v7.0.0/management/api-product-subscriptions/API_PRODUCT_SUBSCRIPTION_ID/status` +|- [Delete Api Product Subscription](${apiExplorerUrl}/resource-docs/OBPv7.0.0?operationid=OBPv7.0.0-deleteApiProductSubscription): `DELETE /obp/v7.0.0/management/api-product-subscriptions/API_PRODUCT_SUBSCRIPTION_ID` | """) @@ -3878,7 +3893,7 @@ object Glossary extends MdcLoggable { | |* UserId may be stored for audit purposes but is **ignored in queries** |* All authorized users see the same shared data -|* Role-based authorization is **required** (e.g., CanGetDynamicEntity_FooBar) +|* Role-based authorization is **required** (e.g., CanGetDynamicEntityRecord_FooBar) |* Cascade delete **is allowed** - you can delete the entity definition and all its records in one operation | |**Summary table:** @@ -3900,10 +3915,10 @@ object Glossary extends MdcLoggable { | |When you create a Dynamic Entity named 'FooBar', OBP automatically creates these roles: | -|* CanCreateDynamicEntity_FooBar -|* CanUpdateDynamicEntity_FooBar -|* CanGetDynamicEntity_FooBar -|* CanDeleteDynamicEntity_FooBar +|* CanCreateDynamicEntityRecord_FooBar +|* CanUpdateDynamicEntityRecord_FooBar +|* CanGetDynamicEntityRecord_FooBar +|* CanDeleteDynamicEntityRecord_FooBar |* CanGrantDynamicEntityRowAccess_FooBar (only meaningful when the entity uses row-level access, see below) | |**Field-level write/read permissions (per property):** @@ -3927,12 +3942,15 @@ object Glossary extends MdcLoggable { | |Set `useRowLevelAccess` on the definition (`use_row_level_access` in the v6.0.0 snake_case request) to decide access **per record** instead of by the entity's roles. The entity's Get, Update and Delete roles then stop gating the shared routes and an access list on each record decides, carrying four permissions per User: `can_read`, `can_update`, `can_delete` and `can_grant`. | -|* The User who creates a record holds all four on it, so they share their own records without holding any role. Creating a record still needs CanCreateDynamicEntity_FooBar. +|* The User who creates a record holds all four on it, so they share their own records without holding any role. Creating a record still needs CanCreateDynamicEntityRecord_FooBar. |* Records the caller may not read are omitted from list responses and return 404 individually, so a record's existence is not disclosed. -|* `GET /obp/dynamic-entity/FooBar/FOO_BAR_ID/access` lists the access list; `POST` to the same URL grants or updates one entry (or an array of them) — `user_id` is required, `can_read`/`can_update`/`can_delete` default to `false` and `can_grant` defaults to `true`, so a grantee may re-share; `DELETE /obp/dynamic-entity/FooBar/FOO_BAR_ID/access/USER_ID` revokes, cascading to the grants that User passed on. Bank level entities take the same paths under `/banks/BANK_ID/`. +|* `GET /obp/dynamic-entity/FooBar/FOO_BAR_ID/access` lists the access list. `PUT` to the same URL grants or updates one entry, or an array of them. Each entry names a `user_id` or an `organisation_id`. `can_read`, `can_update` and `can_delete` default to `false`. `can_grant` defaults to `true` for a User, so a grantee may share further, and to `false` for an Organisation. +|* `DELETE /obp/dynamic-entity/FooBar/FOO_BAR_ID/access/USER_ID` revokes a User, and also removes the grants that User passed on. `DELETE .../access/organisations/ORGANISATION_ID` revokes an Organisation. Bank level entities take the same paths under `/banks/BANK_ID/`. +|* A grant to an Organisation gives its permissions to every member while the Organisation is active. Access follows membership: people who join get it and people who leave lose it, with no change to the grant. This is how a team shares records, for example one survey answer per team. |* CanGrantDynamicEntityRowAccess_FooBar (CanGrantDynamicEntityRowAccess_SystemFooBar at system level) administers the access list of any record. |* Field-level read and write roles still apply on top of the access list. -|* `useRowLevelAccess` cannot be combined with `hasPublicAccess` or `hasCommunityAccess`, and is only supported for locally-backed entities (an entity routed to an external connector for `dynamicEntityProcess` cannot enforce the access list). +|* `useRowLevelAccess` cannot be combined with `hasPublicAccess`. It can be combined with `hasCommunityAccess`: a holder of CanGetDynamicEntityRecord_FooBar then reads every record through `/obp/dynamic-entity/community/FooBar`, read-only, while everyone else reads only the records shared with them. This is how staff read everything in a programme where each team sees only its own records. +|* `useRowLevelAccess` is only supported for locally-backed entities. An entity routed to an external connector for `dynamicEntityProcess` cannot enforce the access list. | |See ${getGlossaryItemLink("Dynamic-Entity-Access-Model")} for how this sits alongside the other routes. | @@ -4102,9 +4120,9 @@ object Glossary extends MdcLoggable { || Personal: `/obp/dynamic-entity/my/ENTITY` | `hasPersonalEntity` | any authenticated User; a role only if `personalRequiresRole`; a consent user in addition only if its Consent lists the entity in `my_resources` | same rule | the caller's own rows only, keyed by the on-behalf-of user | || Community: `/obp/dynamic-entity/community/ENTITY` | `hasCommunityAccess` | authenticated holders of the Get role | nobody (read only) | every row, personal rows included | || Public: `/obp/dynamic-entity/public/ENTITY` | `hasPublicAccess` | anyone, no login | nobody (read only) | the shared pool only | -|| Row level: the System routes with `useRowLevelAccess` | `useRowLevelAccess` | per row, whoever the access list marks readable; lists are filtered | per row, access list Update and Delete; the creator is granted read, update, delete and grant on their own row | whatever the access list says | +|| Row level: the System routes with `useRowLevelAccess` | `useRowLevelAccess` | per row, whoever the access list marks readable, directly or as a member of an active Organisation on the list; lists are filtered | per row, access list Update and Delete; the creator is granted read, update, delete and grant on their own row | whatever the access list says | | -|The entity roles are named after the entity: `CanCreateDynamicEntity_SystemENTITY`, `CanGetDynamicEntity_SystemENTITY`, `CanUpdateDynamicEntity_SystemENTITY`, `CanDeleteDynamicEntity_SystemENTITY` (without `System` for bank level entities, held at the bank). +|The entity roles are named after the entity: `CanCreateDynamicEntityRecord_ENTITY`, `CanGetDynamicEntityRecord_ENTITY`, `CanUpdateDynamicEntityRecord_ENTITY` and `CanDeleteDynamicEntityRecord_ENTITY`. The name carries no space: each Role is held at the entity's space, `SYS` for a system entity or the bank's id for a bank level one. | |Two settings apply on top of the routes: | @@ -4116,10 +4134,11 @@ object Glossary extends MdcLoggable { || Call | Does | ||---|---| || `GET /obp/dynamic-entity/ENTITY/RECORD_ID/access` | lists who may read, update, delete and grant this record, and who granted them | -|| `PUT /obp/dynamic-entity/ENTITY/RECORD_ID/access` | grants or replaces one entry, or an array of them: `user_id` is required, `can_read`, `can_update` and `can_delete` default to `false`, `can_grant` defaults to `true` | -|| `DELETE /obp/dynamic-entity/ENTITY/RECORD_ID/access/USER_ID` | revokes that User, cascading to every grant they passed on | +|| `PUT /obp/dynamic-entity/ENTITY/RECORD_ID/access` | grants or replaces one entry, or an array of them. Each entry names a `user_id` or an `organisation_id`. `can_read`, `can_update` and `can_delete` default to `false`. `can_grant` defaults to `true` for a User and `false` for an Organisation | +|| `DELETE /obp/dynamic-entity/ENTITY/RECORD_ID/access/USER_ID` | revokes that User, and every grant they passed on | +|| `DELETE /obp/dynamic-entity/ENTITY/RECORD_ID/access/organisations/ORGANISATION_ID` | revokes that Organisation; its members lose the access it gave them | | -|Bank level entities take the same paths under `/banks/BANK_ID/`. The caller needs `can_grant` on the record — the User who created it has it — or `CanGrantDynamicEntityRowAccess_SystemENTITY` (`CanGrantDynamicEntityRowAccess_ENTITY` at a bank), which administers any record. The calls return 400 on an entity that is not row level. Creating a record still takes the entity's Create role, and `useRowLevelAccess` is only supported for locally-backed entities. +|Bank level entities take the same paths under `/banks/BANK_ID/`. The caller needs `can_grant` on the record, which the User who created it has. Members of an Organisation have it too if the Organisation was granted it. Otherwise the caller needs `CanGrantDynamicEntityRowAccess_ENTITY`, held at the entity's space, which administers any record. The calls return 400 on an entity that is not row level. Creating a record still takes the entity's Create role, and `useRowLevelAccess` is only supported for locally-backed entities. | |**Authorship and editing by actor** | @@ -4141,6 +4160,7 @@ object Glossary extends MdcLoggable { || Team space | personal on, `personalRequiresRole` on, community on | members write their own rows, the whole team reads everything; the entity roles define the team | || User owned records | personal on, `personalRequiresRole` off, community off, public off | each User has their own rows; an agent reaches them only through a Consent whose `my_resources` lists the entity | || Shared records with per row sharing | `useRowLevelAccess` on | the creator owns the row and grants others read, update, delete or grant | +|| Records per team, read in full by staff | `useRowLevelAccess` on, community on | each record is shared with one team's Organisation, so each team sees only its own; staff with the Get role read every record through `community` | | |One combination deserves care: personal on, `personalRequiresRole` off, community on. It shows every User's personal rows to any holder of the Get role, which is rarely intended. | @@ -7453,6 +7473,8 @@ object Glossary extends MdcLoggable { |## How it uses OBP-API | |OBP-API is Cohort's only backend. Its records are Dynamic Entities in a space of its own, and it uses OBP's Users, login, Roles, Customers, Files and messages. Cohort is a Platform App: it declares the Scopes it needs, and an administrator grants them. +| +|Each startup is a team: an ${getGlossaryItemLink("Organisation")} its founder creates, at `SYS`, and Cohort records its `organisation_id`. Every member of the team sees the programme. A survey is answered once per team: the answers are a row-level record shared with the team's Organisation, so every member can read and edit them, and staff read all the answers through community access. See ${getGlossaryItemLink("Dynamic-Entity-Access-Model")}. | |It is part of the OBP-Frontend repository (`apps/cohort`). See https://cohort.tesobe.com. |""".stripMargin) @@ -7479,6 +7501,25 @@ object Glossary extends MdcLoggable { |## How it uses OBP-API | |Conformator is two Platform Apps in the OBP-Frontend repository: the web app (`apps/conformator`) and the runner (`apps/conformator-runner`). The runner carries out the tests and records each result. Both keep their records in OBP-API as Dynamic Entities, in a central space and in each participant's space, and each declares the Scopes it needs. +| +|Each participant has an ${getGlossaryItemLink("Organisation")}, which regulator staff create when they register it, naming its first admin. From then on the participant's admins add and remove their own people. Conformator gives the Organisation's members the participant Roles in the participant's space, and takes them away from people who leave, with `DELETE /obp/v7.0.0/banks/BANK_ID/entitlements/ENTITLEMENT_ID`. + |""".stripMargin) + + + glossaryItems += GlossaryItem( + title = "OBP-Stripe", + description = + s""" + |# OBP-Stripe + | + |**OBP-Stripe** takes card payments for API Products through Stripe, and keeps each ${getGlossaryItemLink("API Product Subscription")} in step with Stripe. + | + |- **Prices:** OBP-API is the source of truth. OBP-Stripe reads the API Products whose `BILLING_SYSTEM` attribute is `stripe`, and keeps a monthly Stripe Price for each one, from `monthly_subscription_amount` and `monthly_subscription_currency`. + |- **Checkout:** a developer subscribes a Consumer in the Portal, and the subscription starts as `requested`. The Portal sends them to OBP-Stripe, which checks that they may act for the Consumer, then starts a Stripe Checkout. Members of an ${getGlossaryItemLink("Organisation")} can pay for its Consumers' subscriptions. + |- **Status:** Stripe's webhooks, and a check every 5 minutes, set the subscription to `active`, `past_due`, `suspended` or `cancelled`. OBP-API grants and removes access on each status, so OBP-Stripe never grants a Role or Scope itself. A subscription cancelled in OBP is cancelled in Stripe. + |- **Billing:** each person's Stripe customer is kept in their non-personal user attribute `STRIPE_CUSTOMER_ID`, and they change their card or download invoices on Stripe's billing page. + | + |OBP-Stripe is a Platform App: it calls OBP-API with its own token, and declares the Scopes it needs. See ${getGlossaryItemLink("Platform Apps")}. |""".stripMargin) @@ -7902,6 +7943,56 @@ object Glossary extends MdcLoggable { |- [Delete Tenant](${apiExplorerUrl}/resource-docs/OBPv7.0.0?operationid=OBPv7.0.0-deleteTenant): `DELETE /obp/v7.0.0/tenants/TENANT_ID` |""".stripMargin) + glossaryItems += GlossaryItem( + title = "Organisation", + description = + s""" + |# Organisation + | + |An **Organisation** is a group of people that uses the APIs and owns Consumers. It is most likely a fintech or another external group, or an informal group within a bank. It has members. + | + |An Organisation has no direct legal relationship with a bank. That is what a Customer is: a legal person or entity with a formal relationship with a bank on this instance. Where an Organisation does have such a relationship, it comes through a link to the Customer the bank keeps for it. That link is not built yet. + | + |An Organisation is not a ${getGlossaryItemLink("Tenant")} either. A Tenant is a customer of the operator of this OBP instance. The fintechs building on a bank's APIs are one level down. + | + |Anyone who is logged in can create an Organisation, and becomes its first admin. Each member is an `admin` or a `member`. An Organisation always keeps at least one admin. + | + |## Who may act for a Consumer + | + |No Role is needed to act for your own Consumers: + | + |* A Consumer that belongs to no Organisation is owned by the User who created it. + |* A Consumer that belongs to an active Organisation is owned by the Organisation's members. Its creator no longer owns it on their own, so it stays with the team when someone leaves. + | + |Owners read their Consumers, their usage, Scopes and API Product Subscriptions under `/my/consumers`, and subscribe them to API Products. Admins also change the Organisation and its members, and move Consumers into or out of it. + | + |## Sharing Dynamic Entity records + | + |A record of a Dynamic Entity with row-level access can be shared with an Organisation as well as with single Users: `PUT .../RECORD_ID/access` with an `organisation_id`. Every member of the active Organisation then holds the permissions given, and access follows membership. See ${getGlossaryItemLink("Dynamic-Entity-Access-Model")}. + | + |## bank_id + | + |Every Organisation has a `bank_id`: the space that administers it. It says where staff Roles for the Organisation are held, and it never changes. It is not a legal relationship with that bank. + | + |An Organisation you create for yourself is always at SYS. Only staff with CanCreateOrganisationAtOneBank at a bank can create an Organisation there, so each bank decides which Organisations it administers. An application that only needs to know which Organisation is which, such as a programme recording its startups' teams, keeps the `organisation_id` in its own records. + | + |## Staff + | + |Staff Roles are held at the Organisation's `bank_id`. With CanCreateOrganisationAtOneBank, staff create an Organisation for someone else and name its first admin, for example when a regulator registers a participant. With CanGetOrganisationAtOneBank they read Organisations and their members. With CanUpdateOrganisationStatusAtOneBank they suspend one: its members still see it, but cannot act for its Consumers. + | + |## Endpoints + | + |- [Create My Organisation](${apiExplorerUrl}/resource-docs/OBPv7.0.0?operationid=OBPv7.0.0-createMyOrganisation): `POST /obp/v7.0.0/my/organisations` + |- [Get My Organisations](${apiExplorerUrl}/resource-docs/OBPv7.0.0?operationid=OBPv7.0.0-getMyOrganisations): `GET /obp/v7.0.0/my/organisations` + |- [Add My Organisation Member](${apiExplorerUrl}/resource-docs/OBPv7.0.0?operationid=OBPv7.0.0-addMyOrganisationMember): `POST /obp/v7.0.0/my/organisations/ORGANISATION_ID/members` + |- [Update My Consumer Organisation](${apiExplorerUrl}/resource-docs/OBPv7.0.0?operationid=OBPv7.0.0-updateMyConsumerOrganisation): `PUT /obp/v7.0.0/my/consumers/CONSUMER_ID/organisation` + |- [Get My Consumers](${apiExplorerUrl}/resource-docs/OBPv7.0.0?operationid=OBPv7.0.0-getMyConsumers): `GET /obp/v7.0.0/my/consumers` + |- [Get My Consumer Usage](${apiExplorerUrl}/resource-docs/OBPv7.0.0?operationid=OBPv7.0.0-getMyConsumerUsage): `GET /obp/v7.0.0/my/consumers/CONSUMER_ID/usage` + |- [Create Organisation](${apiExplorerUrl}/resource-docs/OBPv7.0.0?operationid=OBPv7.0.0-createOrganisation): `POST /obp/v7.0.0/management/organisations` + |- [Get Organisations](${apiExplorerUrl}/resource-docs/OBPv7.0.0?operationid=OBPv7.0.0-getOrganisations): `GET /obp/v7.0.0/management/organisations` + |- [Get Organisation Members](${apiExplorerUrl}/resource-docs/OBPv7.0.0?operationid=OBPv7.0.0-getOrganisationMembers): `GET /obp/v7.0.0/management/organisations/ORGANISATION_ID/members` + |""".stripMargin) + glossaryItems += GlossaryItem( title = "Data Retention", description = diff --git a/obp-api/src/main/scala/code/api/v4_0_0/Http4s400.scala b/obp-api/src/main/scala/code/api/v4_0_0/Http4s400.scala index c2de505302..8e44c62189 100644 --- a/obp-api/src/main/scala/code/api/v4_0_0/Http4s400.scala +++ b/obp-api/src/main/scala/code/api/v4_0_0/Http4s400.scala @@ -4299,9 +4299,18 @@ object Http4s400 { postJson.bank_id.map(BankId(_)), postJson.account_routing.scheme, Some(cc)) + // The accounts the caller can see through the owner view. Only these are matched, so the + // regex never runs against, and the response never tells anything about, other users' accounts. + ownerViewAccounts <- Views.views.vend.getPrivateBankAccountsFuture( + user, List(ViewId(Constant.SYSTEM_OWNER_VIEW_ID))) + ownerViewAccountSet = ownerViewAccounts.toSet accountRoutingAddressRegex = postJson.account_routing.address.r - filteredAccountRoutings = accountRoutings.filter(accountRouting => - accountRoutingAddressRegex.findFirstIn(accountRouting.accountRouting.address).isDefined) + // Other users' accounts are skipped silently before the regex runs, as if they did not exist. + filteredAccountRoutings = accountRoutings + .filter(accountRouting => ownerViewAccountSet.contains( + BankIdAccountId(accountRouting.bankId, accountRouting.accountId))) + .filter(accountRouting => + accountRoutingAddressRegex.findFirstIn(accountRouting.accountRouting.address).isDefined) accountsJson <- Future.sequence( filteredAccountRoutings.map(accountRouting => for { diff --git a/obp-api/src/main/scala/code/api/v6_0_0/Http4s600.scala b/obp-api/src/main/scala/code/api/v6_0_0/Http4s600.scala index 8331b8b9ea..112f52f579 100644 --- a/obp-api/src/main/scala/code/api/v6_0_0/Http4s600.scala +++ b/obp-api/src/main/scala/code/api/v6_0_0/Http4s600.scala @@ -3925,7 +3925,8 @@ object Http4s600 { } lazy val editBankChatMessage: Http4sRoute = Http4sRoute { - case req @ PUT -> `prefixPath` / "banks" / _ / "chat-rooms" / chatRoomId / "messages" / chatMessageId => + // bankIdStr is read so the room can be checked against the bank in the path + case req @ PUT -> `prefixPath` / "banks" / bankIdStr / "chat-rooms" / chatRoomId / "messages" / chatMessageId => EndpointHelpers.withUserAndBank(req) { (user, _, cc) => val rawBody = cc.httpBody.getOrElse("") for { @@ -3942,10 +3943,13 @@ object Http4s600 { s"$ChatMessageLinkHostNotAllowed Disallowed host(s): ${badLinkHosts.mkString(", ")}", cc = Some(cc)) { badLinkHosts.isEmpty } roomBox <- Future(code.chat.ChatRoomTrait.chatRoomProvider.vend.getChatRoom(chatRoomId)) - _ <- Future(unboxFullOrFail(roomBox, Some(cc), ChatRoomNotFound, 404)) + room <- Future(unboxFullOrFail(roomBox, Some(cc), ChatRoomNotFound, 404)) + // the room must belong to the bank in the path, else it is treated as not found + _ <- Helper.booleanToFuture(ChatRoomNotFound, 404, cc = Some(cc)) { room.bankId == bankIdStr } partBox <- Future(code.chat.ChatPermissions.isParticipant(chatRoomId, user.userId)) _ <- Future(unboxFullOrFail(partBox, Some(cc), NotChatRoomParticipant, 403)) - msgBox <- Future(code.chat.ChatMessageTrait.chatMessageProvider.vend.getMessage(chatMessageId)) + // the message must be in the room in the path, else being a participant of one room lets a user edit their messages in any room + msgBox <- Future(code.chat.ChatMessageTrait.chatMessageProvider.vend.getMessage(chatMessageId).filter(_.chatRoomId == chatRoomId)) msg <- Future(unboxFullOrFail(msgBox, Some(cc), ChatMessageNotFound, 404)) _ <- Helper.booleanToFuture(CannotEditOthersMessage, cc = Some(cc)) { msg.senderUserId == user.userId @@ -3981,7 +3985,8 @@ object Http4s600 { _ <- Future(unboxFullOrFail(roomBox, Some(cc), ChatRoomNotFound, 404)) partBox <- Future(code.chat.ChatPermissions.isParticipant(chatRoomId, user.userId)) _ <- Future(unboxFullOrFail(partBox, Some(cc), NotChatRoomParticipant, 403)) - msgBox <- Future(code.chat.ChatMessageTrait.chatMessageProvider.vend.getMessage(chatMessageId)) + // the message must be in the room in the path, else being a participant of one room lets a user edit their messages in any room + msgBox <- Future(code.chat.ChatMessageTrait.chatMessageProvider.vend.getMessage(chatMessageId).filter(_.chatRoomId == chatRoomId)) msg <- Future(unboxFullOrFail(msgBox, Some(cc), ChatMessageNotFound, 404)) _ <- Helper.booleanToFuture(CannotEditOthersMessage, cc = Some(cc)) { msg.senderUserId == user.userId @@ -7392,7 +7397,7 @@ object Http4s600 { |* Who may use the entity's data endpoints is set by its Roles: a person needs a Role as an Entitlement. An application acting as itself needs it as a Scope, and its Consumer must be a Platform App. |* Set `has_community_access` to `true` to generate read-only community endpoints (GET only, authentication required + CanGet role) under `/community/`. Community endpoints return ALL records (personal + non-personal from all users). |* Set `personal_requires_role` to `true` to require the corresponding role (e.g. CanCreateDynamicEntity_, CanGetDynamicEntity_) for `/my/` personal entity endpoints. Default is `false` (any authenticated user can use `/my/` endpoints). - |* Set `use_row_level_access` to `true` to decide read, update, delete and grant **per record** with an access list, in place of the entity's Get, Update and Delete roles. The User who creates a record holds all four permissions on it and shares it with `GET/PUT /obp/dynamic-entity/ENTITY_NAME/RECORD_ID/access` (a body of `user_id`, `can_read`, `can_update`, `can_delete`, `can_grant`) and `DELETE /obp/dynamic-entity/ENTITY_NAME/RECORD_ID/access/USER_ID`; revoking cascades to the grants that user passed on. Records the caller may not read are omitted from list responses and return 404 individually. Creating a record still needs the entity's Create role, `CanGrantDynamicEntityRowAccess_` administers the access list of any record, and field-level read and write roles still apply on top. It cannot be combined with `has_public_access` or `has_community_access`, and is only supported for locally-backed entities. + |* Set `use_row_level_access` to `true` to decide read, update, delete and grant **per record** with an access list, in place of the entity's Get, Update and Delete roles. The User who creates a record holds all four permissions on it. They share it with `GET/PUT /obp/dynamic-entity/ENTITY_NAME/RECORD_ID/access`, with a body naming a `user_id` or an `organisation_id` and the four permissions. They take access away with `DELETE /obp/dynamic-entity/ENTITY_NAME/RECORD_ID/access/USER_ID` or `.../access/organisations/ORGANISATION_ID`. Revoking a User also removes the grants that User passed on. A grant to an Organisation applies to its members while it is active, so access follows membership. Records the caller may not read are omitted from list responses and return 404 individually. Creating a record still needs the entity's Create role, `CanGrantDynamicEntityRowAccess_` administers the access list of any record, and field-level read and write roles still apply on top. It cannot be combined with `has_public_access`. It can be combined with `has_community_access`: a holder of the entity's Get role then reads every record through the community URL, while everyone else reads only the records shared with them. It is only supported for locally-backed entities. | |For more information see ${Glossary.getGlossaryItemLink("Dynamic-Entities")} and ${Glossary.getGlossaryItemLink("Dynamic-Entity-Access-Model")}""", CreateDynamicEntityRequestJsonV600( @@ -7464,7 +7469,7 @@ object Http4s600 { |* Who may use the entity's data endpoints is set by its Roles: a person needs a Role as an Entitlement. An application acting as itself needs it as a Scope, and its Consumer must be a Platform App. |* Set `has_community_access` to `true` to generate read-only community endpoints (GET only, authentication required + CanGet role) under `/community/`. Community endpoints return ALL records (personal + non-personal from all users). |* Set `personal_requires_role` to `true` to require the corresponding role (e.g. CanCreateDynamicEntity_, CanGetDynamicEntity_) for `/my/` personal entity endpoints. Default is `false` (any authenticated user can use `/my/` endpoints). - |* Set `use_row_level_access` to `true` to decide read, update, delete and grant **per record** with an access list, in place of the entity's Get, Update and Delete roles. The User who creates a record holds all four permissions on it and shares it with `GET/PUT /obp/dynamic-entity/ENTITY_NAME/RECORD_ID/access` (a body of `user_id`, `can_read`, `can_update`, `can_delete`, `can_grant`) and `DELETE /obp/dynamic-entity/ENTITY_NAME/RECORD_ID/access/USER_ID`; revoking cascades to the grants that user passed on. Records the caller may not read are omitted from list responses and return 404 individually. Creating a record still needs the entity's Create role, `CanGrantDynamicEntityRowAccess_` administers the access list of any record, and field-level read and write roles still apply on top. It cannot be combined with `has_public_access` or `has_community_access`, and is only supported for locally-backed entities. + |* Set `use_row_level_access` to `true` to decide read, update, delete and grant **per record** with an access list, in place of the entity's Get, Update and Delete roles. The User who creates a record holds all four permissions on it. They share it with `GET/PUT /obp/dynamic-entity/ENTITY_NAME/RECORD_ID/access`, with a body naming a `user_id` or an `organisation_id` and the four permissions. They take access away with `DELETE /obp/dynamic-entity/ENTITY_NAME/RECORD_ID/access/USER_ID` or `.../access/organisations/ORGANISATION_ID`. Revoking a User also removes the grants that User passed on. A grant to an Organisation applies to its members while it is active, so access follows membership. Records the caller may not read are omitted from list responses and return 404 individually. Creating a record still needs the entity's Create role, `CanGrantDynamicEntityRowAccess_` administers the access list of any record, and field-level read and write roles still apply on top. It cannot be combined with `has_public_access`. It can be combined with `has_community_access`: a holder of the entity's Get role then reads every record through the community URL, while everyone else reads only the records shared with them. It is only supported for locally-backed entities. | |For more information see ${Glossary.getGlossaryItemLink("Dynamic-Entities")} and ${Glossary.getGlossaryItemLink("Dynamic-Entity-Access-Model")}""", CreateDynamicEntityRequestJsonV600( @@ -7539,7 +7544,7 @@ object Http4s600 { |* Who may use the entity's data endpoints is set by its Roles: a person needs a Role as an Entitlement. An application acting as itself needs it as a Scope, and its Consumer must be a Platform App. |* Set `has_community_access` to `true` to generate read-only community endpoints (GET only, authentication required + CanGet role) under `/community/`. Community endpoints return ALL records (personal + non-personal from all users). |* Set `personal_requires_role` to `true` to require the corresponding role (e.g. CanCreateDynamicEntity_, CanGetDynamicEntity_) for `/my/` personal entity endpoints. Default is `false` (any authenticated user can use `/my/` endpoints). - |* Set `use_row_level_access` to `true` to decide read, update, delete and grant **per record** with an access list, in place of the entity's Get, Update and Delete roles. The User who creates a record holds all four permissions on it and shares it with `GET/PUT /obp/dynamic-entity/ENTITY_NAME/RECORD_ID/access` (a body of `user_id`, `can_read`, `can_update`, `can_delete`, `can_grant`) and `DELETE /obp/dynamic-entity/ENTITY_NAME/RECORD_ID/access/USER_ID`; revoking cascades to the grants that user passed on. Records the caller may not read are omitted from list responses and return 404 individually. Creating a record still needs the entity's Create role, `CanGrantDynamicEntityRowAccess_` administers the access list of any record, and field-level read and write roles still apply on top. It cannot be combined with `has_public_access` or `has_community_access`, and is only supported for locally-backed entities. + |* Set `use_row_level_access` to `true` to decide read, update, delete and grant **per record** with an access list, in place of the entity's Get, Update and Delete roles. The User who creates a record holds all four permissions on it. They share it with `GET/PUT /obp/dynamic-entity/ENTITY_NAME/RECORD_ID/access`, with a body naming a `user_id` or an `organisation_id` and the four permissions. They take access away with `DELETE /obp/dynamic-entity/ENTITY_NAME/RECORD_ID/access/USER_ID` or `.../access/organisations/ORGANISATION_ID`. Revoking a User also removes the grants that User passed on. A grant to an Organisation applies to its members while it is active, so access follows membership. Records the caller may not read are omitted from list responses and return 404 individually. Creating a record still needs the entity's Create role, `CanGrantDynamicEntityRowAccess_` administers the access list of any record, and field-level read and write roles still apply on top. It cannot be combined with `has_public_access`. It can be combined with `has_community_access`: a holder of the entity's Get role then reads every record through the community URL, while everyone else reads only the records shared with them. It is only supported for locally-backed entities. | |For more information see ${Glossary.getGlossaryItemLink("Dynamic-Entities")} and ${Glossary.getGlossaryItemLink("Dynamic-Entity-Access-Model")}""", UpdateDynamicEntityRequestJsonV600( @@ -7603,7 +7608,7 @@ object Http4s600 { |* Who may use the entity's data endpoints is set by its Roles: a person needs a Role as an Entitlement. An application acting as itself needs it as a Scope, and its Consumer must be a Platform App. |* Set `has_community_access` to `true` to generate read-only community endpoints (GET only, authentication required + CanGet role) under `/community/`. Community endpoints return ALL records (personal + non-personal from all users). |* Set `personal_requires_role` to `true` to require the corresponding role (e.g. CanCreateDynamicEntity_, CanGetDynamicEntity_) for `/my/` personal entity endpoints. Default is `false` (any authenticated user can use `/my/` endpoints). - |* Set `use_row_level_access` to `true` to decide read, update, delete and grant **per record** with an access list, in place of the entity's Get, Update and Delete roles. The User who creates a record holds all four permissions on it and shares it with `GET/PUT /obp/dynamic-entity/ENTITY_NAME/RECORD_ID/access` (a body of `user_id`, `can_read`, `can_update`, `can_delete`, `can_grant`) and `DELETE /obp/dynamic-entity/ENTITY_NAME/RECORD_ID/access/USER_ID`; revoking cascades to the grants that user passed on. Records the caller may not read are omitted from list responses and return 404 individually. Creating a record still needs the entity's Create role, `CanGrantDynamicEntityRowAccess_` administers the access list of any record, and field-level read and write roles still apply on top. It cannot be combined with `has_public_access` or `has_community_access`, and is only supported for locally-backed entities. + |* Set `use_row_level_access` to `true` to decide read, update, delete and grant **per record** with an access list, in place of the entity's Get, Update and Delete roles. The User who creates a record holds all four permissions on it. They share it with `GET/PUT /obp/dynamic-entity/ENTITY_NAME/RECORD_ID/access`, with a body naming a `user_id` or an `organisation_id` and the four permissions. They take access away with `DELETE /obp/dynamic-entity/ENTITY_NAME/RECORD_ID/access/USER_ID` or `.../access/organisations/ORGANISATION_ID`. Revoking a User also removes the grants that User passed on. A grant to an Organisation applies to its members while it is active, so access follows membership. Records the caller may not read are omitted from list responses and return 404 individually. Creating a record still needs the entity's Create role, `CanGrantDynamicEntityRowAccess_` administers the access list of any record, and field-level read and write roles still apply on top. It cannot be combined with `has_public_access`. It can be combined with `has_community_access`: a holder of the entity's Get role then reads every record through the community URL, while everyone else reads only the records shared with them. It is only supported for locally-backed entities. | |For more information see ${Glossary.getGlossaryItemLink("Dynamic-Entities")} and ${Glossary.getGlossaryItemLink("Dynamic-Entity-Access-Model")}""", UpdateDynamicEntityRequestJsonV600( @@ -7674,7 +7679,7 @@ object Http4s600 { |* Who may use the entity's data endpoints is set by its Roles: a person needs a Role as an Entitlement. An application acting as itself needs it as a Scope, and its Consumer must be a Platform App. |* Set `has_community_access` to `true` to generate read-only community endpoints (GET only, authentication required + CanGet role) under `/community/`. Community endpoints return ALL records (personal + non-personal from all users). |* Set `personal_requires_role` to `true` to require the corresponding role (e.g. CanCreateDynamicEntity_, CanGetDynamicEntity_) for `/my/` personal entity endpoints. Default is `false` (any authenticated user can use `/my/` endpoints). - |* Set `use_row_level_access` to `true` to decide read, update, delete and grant **per record** with an access list, in place of the entity's Get, Update and Delete roles. The User who creates a record holds all four permissions on it and shares it with `GET/PUT /obp/dynamic-entity/ENTITY_NAME/RECORD_ID/access` (a body of `user_id`, `can_read`, `can_update`, `can_delete`, `can_grant`) and `DELETE /obp/dynamic-entity/ENTITY_NAME/RECORD_ID/access/USER_ID`; revoking cascades to the grants that user passed on. Records the caller may not read are omitted from list responses and return 404 individually. Creating a record still needs the entity's Create role, `CanGrantDynamicEntityRowAccess_` administers the access list of any record, and field-level read and write roles still apply on top. It cannot be combined with `has_public_access` or `has_community_access`, and is only supported for locally-backed entities. + |* Set `use_row_level_access` to `true` to decide read, update, delete and grant **per record** with an access list, in place of the entity's Get, Update and Delete roles. The User who creates a record holds all four permissions on it. They share it with `GET/PUT /obp/dynamic-entity/ENTITY_NAME/RECORD_ID/access`, with a body naming a `user_id` or an `organisation_id` and the four permissions. They take access away with `DELETE /obp/dynamic-entity/ENTITY_NAME/RECORD_ID/access/USER_ID` or `.../access/organisations/ORGANISATION_ID`. Revoking a User also removes the grants that User passed on. A grant to an Organisation applies to its members while it is active, so access follows membership. Records the caller may not read are omitted from list responses and return 404 individually. Creating a record still needs the entity's Create role, `CanGrantDynamicEntityRowAccess_` administers the access list of any record, and field-level read and write roles still apply on top. It cannot be combined with `has_public_access`. It can be combined with `has_community_access`: a holder of the entity's Get role then reads every record through the community URL, while everyone else reads only the records shared with them. It is only supported for locally-backed entities. | |For more information see ${Glossary.getGlossaryItemLink("My-Dynamic-Entities")} and ${Glossary.getGlossaryItemLink("Dynamic-Entity-Access-Model")}""", UpdateDynamicEntityRequestJsonV600( diff --git a/obp-api/src/main/scala/code/api/v7_0_0/Http4s700.scala b/obp-api/src/main/scala/code/api/v7_0_0/Http4s700.scala index d7f20fb876..4950d1dacf 100644 --- a/obp-api/src/main/scala/code/api/v7_0_0/Http4s700.scala +++ b/obp-api/src/main/scala/code/api/v7_0_0/Http4s700.scala @@ -123,13 +123,12 @@ object Http4s700 { * * Pattern: Add nameOf(Implementations{version}.endpointName) :: with a comment explaining why * - * NOTE: Currently empty - no v7-specific exclusions have been identified yet. - * As v7.0.0 introduces endpoints with different URL patterns than previous versions, - * add those old endpoint names here with explanatory comments. + * An excluded endpoint is also not served at v7.0.0: the bridge to v6.0.0 does not pass on a request that one + * of them would serve (see excludedRouteIndex), so it gets a 404. */ lazy val excludeEndpoints: List[String] = - // Add exclusions here when v7.0.0 replaces old endpoints with different URLs - // Example: nameOf(Implementations3_0_0.getUserByUsername) :: // v7.0.0 uses /providers/:provider/users/:username + // v7.0.0 has POST /my/accounts/account-routing-regex-query instead: it searches only the caller's own accounts + nameOf(code.api.v4_0_0.Http4s400.Implementations4_0_0.getAccountsByAccountRoutingRegex) :: Nil /** @@ -534,6 +533,44 @@ object Http4s700 { http4sPartialFunction = Some(deleteEntitlement) ) + // Route: DELETE /obp/v7.0.0/banks/BANK_ID/entitlements/ENTITLEMENT_ID (204) + // The one place CanDeleteEntitlementAtOneBank is checked: someone who manages Roles at one bank can take + // them away there, without the power to delete Entitlements at every bank. + val deleteEntitlementAtOneBank: Http4sRoute = Http4sRoute { + case req @ DELETE -> `prefixPath` / "banks" / _ / "entitlements" / entitlementId => + EndpointHelpers.withUserAndBankDelete(req) { (_, bank, cc) => + for { + entitlement <- Future(Entitlement.entitlement.vend.getEntitlementById(entitlementId) + .filter(_.bankId == bank.bankId.value)) + .map(unboxFullOrFail(_, Some(cc), s"$EntitlementNotFound Current ENTITLEMENT_ID($entitlementId) at BANK_ID(${bank.bankId.value}).", 404)) + _ <- Future(Entitlement.entitlement.vend.deleteEntitlement(Some(entitlement))) + } yield () + } + } + + resourceDocs += ResourceDoc( + implementedInApiVersion, + nameOf(deleteEntitlementAtOneBank), + "DELETE", + "/banks/BANK_ID/entitlements/ENTITLEMENT_ID", + "Delete Entitlement at One Bank", + s"""Delete an Entitlement held at the bank BANK_ID. The Entitlement must be at that bank: one at another + |bank, or a system Entitlement, answers 404 here. + | + |You need CanDeleteEntitlementAtOneBank at BANK_ID, or CanDeleteEntitlementAtAnyBank. So someone who + |manages the Roles at one bank can take them away there, without the power to delete Entitlements at + |every bank. To delete any Entitlement, use Delete Entitlement. + | + |${userAuthenticationMessage(true)} + |""".stripMargin, + EmptyBody, + EmptyBody, + List($AuthenticatedUserIsRequired, UserHasMissingRoles, BankNotFound, EntitlementNotFound, UnknownError), + apiTagEntitlement :: apiTagRole :: Nil, + Some(List(ApiRole.canDeleteEntitlementAtOneBank, canDeleteEntitlementAtAnyBank)), + http4sPartialFunction = Some(deleteEntitlementAtOneBank) + ) + // Category: withUserAndBodyCreated (user auth, body parsing, 201 Created) val addEntitlement: Http4sRoute = Http4sRoute { case req @ POST -> `prefixPath` / "users" / userId / "entitlements" => @@ -6251,7 +6288,7 @@ object Http4s700 { // ─── API Product Subscriptions (see docs/API_PRODUCT_SUBSCRIPTION_PLAN.md) ────────────────── // Rule zero: a developer never needs a role for their own consumers; ownership - // (Consumer.createdByUserId == caller) is checked here. Roles are checked at the PRODUCT's + // (the Consumer's creator, or a member of its Organisation: ConsumerOwnership) is checked here. Roles are checked at the PRODUCT's // bank (…AtOneBank); a billing adapter serving several banks is granted the role at each. // Docs for the management endpoints declare their roles for the catalog but disable auto // validation, because the bank is the subscription's bank, not a BANK_ID in the path. @@ -6260,8 +6297,9 @@ object Http4s700 { private def apiProductAttributeValue(attributes: List[code.apiproductattribute.ApiProductAttributeTrait], name: String): Option[String] = attributes.find(a => a.name.equalsIgnoreCase(name) && a.isActive.getOrElse(true)).map(_.value.trim.toLowerCase) + // The Consumer's creator, or a member of the Organisation it belongs to: see ConsumerOwnership. private def userOwnsConsumer(consumer: code.model.Consumer, userId: String): Boolean = - Option(consumer.createdByUserId.get).exists(_ == userId) + code.organisation.ConsumerOwnership.canActFor(consumer, userId) private def userOwnsSubscription(subscription: ApiProductSubscriptionTrait, userId: String): Future[Boolean] = code.consumer.Consumers.consumers.vend.getConsumerByConsumerIdFuture(subscription.consumerId) @@ -6351,7 +6389,7 @@ object Http4s700 { case req @ GET -> `prefixPath` / "my" / "api-product-subscriptions" => EndpointHelpers.withUser(req) { (user, cc) => for { - consumers <- code.consumer.Consumers.consumers.vend.getConsumersByUserIdFuture(user.userId) + consumers <- code.organisation.ConsumerOwnership.consumersFor(user.userId) (subscriptions, _) <- NewStyle.function.getApiProductSubscriptionsByConsumerIds(consumers.map(_.consumerId.get), Some(cc)) json <- subscriptionsWithAttributesJson(subscriptions, cc) } yield json @@ -7726,6 +7764,10 @@ object Http4s700 { // Tenants: the customers of the operator of this instance. resourceDocs ++= Http4s700Tenants.resourceDocs + // Organisations: a company or team that owns Consumers, and the /my/consumers endpoints its members and a + // Consumer's creator use. + resourceDocs ++= Http4s700Organisations.resourceDocs + // What an OIDC provider reads from OBP-API to finish signing a User in for a Consumer. resourceDocs ++= Http4s700OpenIdConnect.resourceDocs @@ -7738,6 +7780,9 @@ object Http4s700 { // Customers at a bank, each with its Customer Attributes, filtered by Customer Attributes. resourceDocs ++= Http4s700Customers.resourceDocs + // The caller's own accounts whose account routing matches a pattern. + resourceDocs ++= Http4s700MyAccounts.resourceDocs + // The order in which the routes are tried. ResourceDocMiddleware selects the doc of the first // route that serves a request, so it is given this same list: the doc that validates a request // is the doc of the route that runs it. @@ -7771,10 +7816,25 @@ object Http4s700 { private lazy val v7RouteIndex: ResourceDocMatcher.RouteIndex = ResourceDocMatcher.buildRouteIndex(Implementations7_0_0.orderedResourceDocs) + // The older endpoints v7.0.0 does not serve (excludeEndpoints), each under its own version. + private lazy val excludedDocs: List[ResourceDoc] = { + val names = excludeEndpoints.toSet + code.api.util.http4s.Http4sResourceDocAggregation.v600.filter(doc => names.contains(doc.partialFunctionName)).toList + } + private lazy val excludedRouteIndex: ResourceDocMatcher.RouteIndex = ResourceDocMatcher.buildRouteIndex(excludedDocs) + private lazy val excludedVersions: List[String] = excludedDocs.map(_.implementedInApiVersion.apiShortVersion).distinct + + // True when the request, sent to an excluded endpoint's own version, would be served by that endpoint + private def isExcluded(req: Request[IO], rawPath: String): Boolean = + excludedVersions.exists { version => + val there = rawPath.replaceFirst("/obp/v7\\.0\\.0/", s"/obp/$version/") + ResourceDocMatcher.selectByRoute(req.withUri(req.uri.withPath(Uri.Path.unsafeFromString(there))), excludedRouteIndex).nonEmpty + } + private val v700ToV600Bridge: HttpRoutes[IO] = Kleisli[HttpF, Request[IO], Response[IO]] { req => val rawPath = req.uri.path.renderString if (rawPath.startsWith("/obp/v7.0.0/") && - ResourceDocMatcher.selectByRoute(req, v7RouteIndex).isEmpty) { + ResourceDocMatcher.selectByRoute(req, v7RouteIndex).isEmpty && !isExcluded(req, rawPath)) { val rewritten = rawPath.replaceFirst("/obp/v7\\.0\\.0/", "/obp/v6.0.0/") val newUri = req.uri.withPath(Uri.Path.unsafeFromString(rewritten)) code.api.v6_0_0.Http4s600.wrappedRoutesV600Services.run(req.withUri(newUri)) diff --git a/obp-api/src/main/scala/code/api/v7_0_0/Http4s700MyAccounts.scala b/obp-api/src/main/scala/code/api/v7_0_0/Http4s700MyAccounts.scala new file mode 100644 index 0000000000..05283a5c0c --- /dev/null +++ b/obp-api/src/main/scala/code/api/v7_0_0/Http4s700MyAccounts.scala @@ -0,0 +1,148 @@ +/** +Open Bank Project - API +Copyright (C) 2011-2026, TESOBE GmbH. + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +Email: contact@tesobe.com +TESOBE GmbH. +Osloer Strasse 16/17 +Berlin 13359, Germany + +This product includes software developed at +TESOBE (http://www.tesobe.com/) + + */ +package code.api.v7_0_0 + +import cats.effect.IO +import code.api.Constant +import code.api.Constant.ApiPathZero +import code.api.ResourceDocs1_4_0.SwaggerDefinitionsJSON.{bankAccountRoutingJson, moderatedAccountsJSON400} +import code.api.util.APIUtil.{Http4sRoute, _} +import code.api.util.ApiTag._ +import code.api.util.ErrorMessages._ +import code.api.util.http4s.Http4sRequestAttributes.EndpointHelpers +import code.api.util.newstyle.ViewNewStyle +import code.api.util.{CustomJsonFormats, NewStyle} +import code.api.v4_0_0.{BankAccountRoutingJson, JSONFactory400, ModeratedAccountsJSON400} +import code.metadata.tags.Tags +import code.views.Views +import com.github.dwickern.macros.NameOf.nameOf +import com.openbankproject.commons.ExecutionContext.Implicits.global +import com.openbankproject.commons.model.{BankId, BankIdAccountId, ViewId} +import com.openbankproject.commons.util.ApiVersion +import net.liftweb.common.Full +import org.http4s._ +import org.http4s.dsl.io._ +import org.json4s.Formats + +import scala.collection.mutable.ArrayBuffer +import scala.concurrent.Future + +/** + * The caller's own accounts whose account routing matches a pattern. + * + * It replaces POST /obp/v4.0.0/management/accounts/account-routing-regex-query, which v7.0.0 does not serve + * (Http4s700.excludeEndpoints): "management" in that path suggested it searched every account at the bank. + * + * Declared in its own object to keep Http4s700's initialiser under the JVM's 64KB method limit. + */ +object Http4s700MyAccounts { + + implicit val formats: Formats = CustomJsonFormats.formats + + private val implementedInApiVersion = ApiVersion.v7_0_0 + private val prefixPath = Root / ApiPathZero.toString / implementedInApiVersion.toString + + val resourceDocs = ArrayBuffer[ResourceDoc]() + + // Route: POST /obp/v7.0.0/my/accounts/account-routing-regex-query + lazy val getMyAccountsByAccountRoutingRegex: Http4sRoute = Http4sRoute { + case req @ POST -> `prefixPath` / "my" / "accounts" / "account-routing-regex-query" => + EndpointHelpers.withUserAndBody[BankAccountRoutingJson, ModeratedAccountsJSON400](req) { (user, postJson, cc) => + for { + // a pattern that is not a valid regular expression is the caller's mistake, not a server error + addressRegex <- NewStyle.function.tryons(InvalidAccountRoutingAddressRegex, 400, Some(cc)) { + postJson.account_routing.address.r + } + (accountRoutings, _) <- NewStyle.function.getAccountRoutingsByScheme( + postJson.bank_id.map(BankId(_)), postJson.account_routing.scheme, Some(cc)) + // only the caller's own accounts: those they reach through the owner view + myAccounts <- Views.views.vend.getPrivateBankAccountsFuture(user, List(ViewId(Constant.SYSTEM_OWNER_VIEW_ID))) + myAccountSet = myAccounts.toSet + matching = accountRoutings + .filter(routing => myAccountSet.contains(BankIdAccountId(routing.bankId, routing.accountId))) + .filter(routing => addressRegex.findFirstIn(routing.accountRouting.address).isDefined) + accountsJson <- Future.sequence(matching.map { routing => + val bankIdAccountId = BankIdAccountId(routing.bankId, routing.accountId) + for { + (account, _) <- NewStyle.function.getBankAccount(routing.bankId, routing.accountId, Some(cc)) + view <- ViewNewStyle.checkOwnerViewAccessAndReturnOwnerView(user, bankIdAccountId, Some(cc)) + moderatedAccount <- NewStyle.function.moderatedBankAccountCore(account, view, Full(user), Some(cc)) + (accountAttributes, _) <- NewStyle.function.getAccountAttributesByAccount( + account.bankId, account.accountId, Some(cc)) + viewsAvailable = Views.views.vend.privateViewsUserCanAccessForAccount(user, bankIdAccountId) + .map(code.api.v1_2_1.JSONFactory.createViewJSON).sortBy(_.short_name) + tags = Tags.tags.vend.getTagsOnAccount(account.bankId, account.accountId)(view.viewId) + } yield JSONFactory400.createBankAccountJSON(moderatedAccount, viewsAvailable, accountAttributes, tags) + }) + } yield ModeratedAccountsJSON400(accountsJson) + } + } + + resourceDocs += ResourceDoc( + implementedInApiVersion, + nameOf(getMyAccountsByAccountRoutingRegex), + "POST", + "/my/accounts/account-routing-regex-query", + "Get My Accounts by Account Routing Regex", + """Returns your own accounts whose account routing matches a pattern. + | + |Your own accounts are those you can see through the owner view. Other users' accounts are never searched, + |and the response says nothing about them. + | + |Give the routing scheme and a regular expression for the routing address. The `bank_id` field is optional: + |leave it out to search your accounts at every bank. + | + |Examples of a scheme: `IBAN`, `AccountNumber`. + |Examples of an address pattern: `DE175.*`, `55897106215-[A-Z]{3}`. + | + |Use it to find accounts that share part of their routing address. For example, if your account numbers + |are `123456789-EUR` and `123456789-USD`, this body finds both: + | + |``` + |{ + | "bank_id": "BANK_ID", + | "account_routing": { + | "scheme": "AccountNumber", + | "address": "123456789-[A-Z]{3}" + | } + |} + |``` + | + |If none of your accounts match, the list is empty. + | + |This replaces POST /obp/v4.0.0/management/accounts/account-routing-regex-query, which v7.0.0 does not serve. + | + |""".stripMargin, + bankAccountRoutingJson, + moderatedAccountsJSON400, + List($AuthenticatedUserIsRequired, InvalidJsonFormat, InvalidAccountRoutingAddressRegex, $BankAccountNotFound, + UnknownError), + List(apiTagAccount), + None, + http4sPartialFunction = Some(getMyAccountsByAccountRoutingRegex) + ) +} diff --git a/obp-api/src/main/scala/code/api/v7_0_0/Http4s700Organisations.scala b/obp-api/src/main/scala/code/api/v7_0_0/Http4s700Organisations.scala new file mode 100644 index 0000000000..825b286c06 --- /dev/null +++ b/obp-api/src/main/scala/code/api/v7_0_0/Http4s700Organisations.scala @@ -0,0 +1,843 @@ +/** +Open Bank Project - API +Copyright (C) 2011-2026, TESOBE GmbH. + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +Email: contact@tesobe.com +TESOBE GmbH. +Osloer Strasse 16/17 +Berlin 13359, Germany + +This product includes software developed at +TESOBE (http://www.tesobe.com/) + + */ + +package code.api.v7_0_0 + +import code.api.Constant.ApiPathZero +import code.api.util.APIUtil.{EmptyBody, Http4sRoute, ResourceDoc, unboxFullOrFail} +import code.api.util.ApiRole.{canCreateOrganisationAtOneBank, canGetOrganisationAtOneBank, canUpdateOrganisationStatusAtOneBank} +import code.api.util.{APIUtil, ApiRole} +import code.api.Constant.DYNAMIC_ENTITY_SYSTEM_LEVEL_BANK_ID +import code.api.util.ApiTag._ +import code.api.util.ErrorMessages._ +import code.api.util.http4s.Http4sRequestAttributes.EndpointHelpers +import code.api.util.{CallContext, CustomJsonFormats, NewStyle, RateLimitingUtil} +import code.api.v6_0_0.JSONFactory600 +import code.consumer.Consumers +import code.model.Consumer +import code.organisation.{ConsumerOwnership, OrganisationMemberTrait, OrganisationTrait, Organisations} +import code.users.{Users => UserVend} +import code.util.Helper +import com.github.dwickern.macros.NameOf.nameOf +import com.openbankproject.commons.ExecutionContext.Implicits.global +import com.openbankproject.commons.util.ApiVersion +import org.http4s._ +import org.http4s.dsl.io._ +import org.json4s.Formats + +import scala.collection.mutable.ArrayBuffer +import scala.concurrent.Future + +/** + * The v7.0.0 Organisation endpoints, and the endpoints with which the owners of a Consumer read it. + * + * An Organisation is a company or team that uses the APIs, for example a fintech, and owns Consumers. Its + * members may act for its Consumers without a Role; its admins also manage it. The rule is "/my/... is yours, + * /management/... needs a Role". See todo/todo_organisations.md and todo/todo_consumer_owner_access.md. + * + * It is declared in its own object to keep Http4s700's initialiser under the JVM's 64KB method limit. + */ +object Http4s700Organisations { + + implicit val formats: Formats = CustomJsonFormats.formats + + private val implementedInApiVersion = ApiVersion.v7_0_0 + private val prefixPath = Root / ApiPathZero.toString / implementedInApiVersion.toString + + val resourceDocs = ArrayBuffer[ResourceDoc]() + + private val organisationDescription = + """An Organisation is a company or team that uses the APIs, for example a fintech, and owns Consumers. Its + |members are admins or members. Members may act for the Organisation's Consumers without a Role: read + |them, their usage, Scopes and API Product Subscriptions, and subscribe them. Admins also change the + |Organisation and its members, and move Consumers into or out of it. + | + |Its bank_id is the space that administers it, and staff Roles for Organisations are held there. An + |Organisation you create for yourself is at SYS. Only staff with CanCreateOrganisationAtOneBank at a bank + |create one there. The bank_id is not a legal relationship with that bank, which is what a Customer is. An + |Organisation is not a Tenant either: a Tenant is a customer of the operator of this instance.""".stripMargin + + private val consumerOwnerDescription = + """You may read a Consumer here if you created it and it belongs to no Organisation, or if it belongs to an + |active Organisation you are a member of. Any other CONSUMER_ID answers 404. The consumer key and secret + |are never returned.""".stripMargin + + private def validName(name: String): Boolean = name.trim.nonEmpty && name.trim.length <= 255 + + /** SYS, or the id of a bank that exists. */ + private def organisationBankId(given: Option[String], cc: CallContext): Future[String] = { + val bankId = given.map(_.trim).filter(_.nonEmpty).getOrElse(DYNAMIC_ENTITY_SYSTEM_LEVEL_BANK_ID) + Helper.booleanToFuture(InvalidOrganisationBankId, 400, Some(cc))(APIUtil.isBankIdWhereRolesCanBeHeld(bankId, Some(cc))) + .map(_ => bankId) + } + + private def holdsAt(bankId: String, userId: String, role: ApiRole, cc: CallContext): Boolean = + APIUtil.handleAccessControlRegardingEntitlementsAndScopes(bankId, userId, APIUtil.getConsumerPrimaryKey(Some(cc)), role :: Nil) + + /** Whether the Role is held at any bank_id, as an Entitlement of the User or a Scope of the calling Consumer. */ + private def holdsAnywhere(userId: String, role: ApiRole, cc: CallContext): Boolean = { + val asEntitlement = code.entitlement.Entitlement.entitlement.vend.getEntitlementsByUserId(userId) + .map(_.exists(_.roleName == role.toString)).openOr(false) + lazy val asScope = cc.consumer.toOption + .flatMap(consumer => code.scope.Scope.scope.vend.getScopesByConsumerId(consumer.id.get.toString).toOption) + .exists(_.exists(_.roleName == role.toString)) + asEntitlement || asScope + } + + /** Staff Roles are checked at the Organisation's bank_id, which is not in the path. */ + private def staffRoleCheck(bankId: String, userId: String, role: ApiRole, cc: CallContext): Future[Box[Unit]] = + Helper.booleanToFuture(s"$UserHasMissingRoles$role for BankId($bankId).", 403, Some(cc))(holdsAt(bankId, userId, role, cc)) + + private def staffOrganisation(organisationId: String, userId: String, role: ApiRole, cc: CallContext): Future[OrganisationTrait] = + for { + organisation <- Future(Organisations.getOrganisation(organisationId)).map(unboxFullOrFail(_, Some(cc), OrganisationNotFound, 404)) + _ <- staffRoleCheck(organisation.bankId, userId, role, cc) + } yield organisation + + /** The Organisation, if the User is a member of it; otherwise 404, so that it does not show it exists. */ + private def membershipOf(organisationId: String, userId: String, cc: CallContext): Future[(OrganisationTrait, OrganisationMemberTrait)] = + Future { + for { + organisation <- Organisations.getOrganisation(organisationId) + membership <- Organisations.getMember(organisationId, userId) + } yield (organisation, membership) + }.map(unboxFullOrFail(_, Some(cc), OrganisationNotFound, 404)) + + private def requireAdmin(membership: OrganisationMemberTrait, cc: CallContext): Future[Box[Unit]] = + Helper.booleanToFuture(OrganisationAdminRequired, 403, Some(cc))(membership.memberRole == Organisations.RoleAdmin) + + private type Box[T] = net.liftweb.common.Box[T] + + private def membersJson(organisationId: String): Future[OrganisationMembersJsonV700] = Future { + OrganisationMembersJsonV700(Organisations.getMembers(organisationId).map { member => + JSONFactory700Organisations.createMemberJson(member, UserVend.users.vend.getUserByUserId(member.userId).toOption) + }) + } + + /** The bank_id in the request body, if one was sent. */ + private def bankIdInBody(cc: CallContext): Option[String] = + scala.util.Try(com.openbankproject.commons.util.JsonAliases.parse(cc.httpBody.getOrElse("{}")) \ "bank_id").toOption.collect { + case org.json4s.JString(value) if value.trim.nonEmpty => value.trim + } + + /** The Consumer, if the User may act for it; otherwise 404. */ + private def myConsumer(consumerId: String, userId: String, cc: CallContext): Future[Consumer] = + Consumers.consumers.vend.getConsumerByConsumerIdFuture(consumerId) + .map(_.filter(consumer => ConsumerOwnership.canActFor(consumer, userId))) + .map(unboxFullOrFail(_, Some(cc), MyConsumerNotFound, 404)) + + // ─── The caller's Organisations ────────────────────────────────────────── + + // Route: POST /obp/v7.0.0/my/organisations (201) + lazy val createMyOrganisation: Http4sRoute = Http4sRoute { + case req @ POST -> `prefixPath` / "my" / "organisations" => + EndpointHelpers.withUserAndBodyCreated[PostOrganisationJsonV700, MyOrganisationJsonV700](req) { (user, body, cc) => + for { + _ <- Helper.booleanToFuture(InvalidOrganisationName, 400, Some(cc))(validName(Option(body.name).getOrElse(""))) + // A bank_id other than SYS is refused rather than ignored, so the caller knows where the Organisation is. + _ <- Helper.booleanToFuture(MyOrganisationBankIdNotAllowed, 400, Some(cc))(bankIdInBody(cc).forall(_ == DYNAMIC_ENTITY_SYSTEM_LEVEL_BANK_ID)) + organisation <- Future { + Organisations.createOrganisation(DYNAMIC_ENTITY_SYSTEM_LEVEL_BANK_ID, body.name.trim, body.description.getOrElse(""), body.website, user.userId, user.userId) + }.map(unboxFullOrFail(_, Some(cc), CreateOrganisationError, 400)) + membership <- Future(Organisations.getMember(organisation.organisationId, user.userId)) + .map(unboxFullOrFail(_, Some(cc), CreateOrganisationError, 400)) + } yield JSONFactory700Organisations.createMyOrganisationJson(organisation, membership) + } + } + + resourceDocs += ResourceDoc( + implementedInApiVersion, + nameOf(createMyOrganisation), + "POST", + "/my/organisations", + "Create My Organisation", + s"""Create an Organisation. You become its first admin. No Role is needed. + | + |The Organisation is at SYS: staff with Roles at SYS administer it. To create an Organisation at a bank, staff + |with CanCreateOrganisationAtOneBank there use Create Organisation (POST /management/organisations). + | + |$organisationDescription + | + |Authentication is Required.""".stripMargin, + PostOrganisationJsonV700("Example Fintech Ltd", Some("Builds payment apps."), Some("https://fintech.example.com")), + JSONFactory700Organisations.myOrganisationJsonV700Example, + List($AuthenticatedUserIsRequired, InvalidJsonFormat, InvalidOrganisationName, MyOrganisationBankIdNotAllowed, CreateOrganisationError, UnknownError), + apiTagOrganisation :: Nil, + None, + http4sPartialFunction = Some(createMyOrganisation) + ) + + // Route: GET /obp/v7.0.0/my/organisations + lazy val getMyOrganisations: Http4sRoute = Http4sRoute { + case req @ GET -> `prefixPath` / "my" / "organisations" => + EndpointHelpers.withUser(req) { (user, _) => + Future { + MyOrganisationsJsonV700(Organisations.getOrganisationsOfUser(user.userId).map { case (organisation, membership) => + JSONFactory700Organisations.createMyOrganisationJson(organisation, membership) + }) + } + } + } + + resourceDocs += ResourceDoc( + implementedInApiVersion, + nameOf(getMyOrganisations), + "GET", + "/my/organisations", + "Get My Organisations", + s"""Get the Organisations you are a member of, each with your member_role in it. + | + |$organisationDescription + | + |Authentication is Required.""".stripMargin, + EmptyBody, + MyOrganisationsJsonV700(List(JSONFactory700Organisations.myOrganisationJsonV700Example)), + List($AuthenticatedUserIsRequired, UnknownError), + apiTagOrganisation :: Nil, + None, + http4sPartialFunction = Some(getMyOrganisations) + ) + + // Route: GET /obp/v7.0.0/my/organisations/ORGANISATION_ID + lazy val getMyOrganisation: Http4sRoute = Http4sRoute { + case req @ GET -> `prefixPath` / "my" / "organisations" / organisationId => + EndpointHelpers.withUser(req) { (user, cc) => + membershipOf(organisationId, user.userId, cc).map { case (organisation, membership) => + JSONFactory700Organisations.createMyOrganisationJson(organisation, membership) + } + } + } + + resourceDocs += ResourceDoc( + implementedInApiVersion, + nameOf(getMyOrganisation), + "GET", + "/my/organisations/ORGANISATION_ID", + "Get My Organisation", + s"""Get one of your Organisations. An Organisation you are not a member of answers 404. + | + |$organisationDescription + | + |Authentication is Required.""".stripMargin, + EmptyBody, + JSONFactory700Organisations.myOrganisationJsonV700Example, + List($AuthenticatedUserIsRequired, OrganisationNotFound, UnknownError), + apiTagOrganisation :: Nil, + None, + http4sPartialFunction = Some(getMyOrganisation) + ) + + // Route: PUT /obp/v7.0.0/my/organisations/ORGANISATION_ID + lazy val updateMyOrganisation: Http4sRoute = Http4sRoute { + case req @ PUT -> `prefixPath` / "my" / "organisations" / organisationId => + EndpointHelpers.withUserAndBody[PutOrganisationJsonV700, MyOrganisationJsonV700](req) { (user, body, cc) => + for { + (_, membership) <- membershipOf(organisationId, user.userId, cc) + _ <- requireAdmin(membership, cc) + _ <- Helper.booleanToFuture(InvalidOrganisationName, 400, Some(cc))(body.name.forall(validName)) + updated <- Future(Organisations.updateOrganisation(organisationId, body.name.map(_.trim), body.description, body.website)) + .map(unboxFullOrFail(_, Some(cc), UpdateOrganisationError, 400)) + } yield JSONFactory700Organisations.createMyOrganisationJson(updated, membership) + } + } + + resourceDocs += ResourceDoc( + implementedInApiVersion, + nameOf(updateMyOrganisation), + "PUT", + "/my/organisations/ORGANISATION_ID", + "Update My Organisation", + s"""Change the name, description or website of an Organisation. Only its admins may. Fields left out are + |not changed. + | + |$organisationDescription + | + |Authentication is Required.""".stripMargin, + PutOrganisationJsonV700(Some("Example Fintech Ltd"), Some("Builds payment apps."), Some("https://fintech.example.com")), + JSONFactory700Organisations.myOrganisationJsonV700Example, + List($AuthenticatedUserIsRequired, InvalidJsonFormat, OrganisationNotFound, OrganisationAdminRequired, InvalidOrganisationName, + UpdateOrganisationError, UnknownError), + apiTagOrganisation :: Nil, + None, + http4sPartialFunction = Some(updateMyOrganisation) + ) + + // Route: DELETE /obp/v7.0.0/my/organisations/ORGANISATION_ID (204) + lazy val deleteMyOrganisation: Http4sRoute = Http4sRoute { + case req @ DELETE -> `prefixPath` / "my" / "organisations" / organisationId => + EndpointHelpers.withUserDelete(req) { (user, cc) => + for { + (_, membership) <- membershipOf(organisationId, user.userId, cc) + _ <- requireAdmin(membership, cc) + _ <- Helper.booleanToFuture(OrganisationHasConsumers, 409, Some(cc))(ConsumerOwnership.consumerCount(organisationId) == 0) + _ <- Future(Organisations.deleteOrganisation(organisationId)).map(unboxFullOrFail(_, Some(cc), DeleteOrganisationError, 400)) + } yield () + } + } + + resourceDocs += ResourceDoc( + implementedInApiVersion, + nameOf(deleteMyOrganisation), + "DELETE", + "/my/organisations/ORGANISATION_ID", + "Delete My Organisation", + s"""Delete an Organisation and its memberships. Only its admins may, and only when no Consumer belongs to it. + | + |$organisationDescription + | + |Authentication is Required.""".stripMargin, + EmptyBody, + EmptyBody, + List($AuthenticatedUserIsRequired, OrganisationNotFound, OrganisationAdminRequired, OrganisationHasConsumers, + DeleteOrganisationError, UnknownError), + apiTagOrganisation :: Nil, + None, + http4sPartialFunction = Some(deleteMyOrganisation) + ) + + // ─── Members ───────────────────────────────────────────────────────────── + + // Route: GET /obp/v7.0.0/my/organisations/ORGANISATION_ID/members + lazy val getMyOrganisationMembers: Http4sRoute = Http4sRoute { + case req @ GET -> `prefixPath` / "my" / "organisations" / organisationId / "members" => + EndpointHelpers.withUser(req) { (user, cc) => + for { + _ <- membershipOf(organisationId, user.userId, cc) + members <- membersJson(organisationId) + } yield members + } + } + + resourceDocs += ResourceDoc( + implementedInApiVersion, + nameOf(getMyOrganisationMembers), + "GET", + "/my/organisations/ORGANISATION_ID/members", + "Get My Organisation Members", + s"""Get the members of one of your Organisations, with their member_role. + | + |$organisationDescription + | + |Authentication is Required.""".stripMargin, + EmptyBody, + OrganisationMembersJsonV700(List(JSONFactory700Organisations.organisationMemberJsonV700Example)), + List($AuthenticatedUserIsRequired, OrganisationNotFound, UnknownError), + apiTagOrganisation :: Nil, + None, + http4sPartialFunction = Some(getMyOrganisationMembers) + ) + + // Route: POST /obp/v7.0.0/my/organisations/ORGANISATION_ID/members (201) + lazy val addMyOrganisationMember: Http4sRoute = Http4sRoute { + case req @ POST -> `prefixPath` / "my" / "organisations" / organisationId / "members" => + EndpointHelpers.withUserAndBodyCreated[PostOrganisationMemberJsonV700, OrganisationMemberJsonV700](req) { (user, body, cc) => + for { + (_, membership) <- membershipOf(organisationId, user.userId, cc) + _ <- requireAdmin(membership, cc) + _ <- Helper.booleanToFuture(InvalidOrganisationMemberRole, 400, Some(cc))(Organisations.ValidMemberRoles.contains(body.member_role)) + (newMember, _) <- NewStyle.function.findByUserId(body.user_id, Some(cc)) + _ <- Helper.booleanToFuture(OrganisationMemberAlreadyExists, 409, Some(cc))(Organisations.getMember(organisationId, newMember.userId).isEmpty) + added <- Future(Organisations.addMember(organisationId, newMember.userId, body.member_role, user.userId)) + .map(unboxFullOrFail(_, Some(cc), UpdateOrganisationMemberError, 400)) + } yield JSONFactory700Organisations.createMemberJson(added, Some(newMember)) + } + } + + resourceDocs += ResourceDoc( + implementedInApiVersion, + nameOf(addMyOrganisationMember), + "POST", + "/my/organisations/ORGANISATION_ID/members", + "Add My Organisation Member", + s"""Add a User to one of your Organisations, as admin or member. Only its admins may. The new member can + |read their user_id from Get Current User. + | + |$organisationDescription + | + |Authentication is Required.""".stripMargin, + PostOrganisationMemberJsonV700("9ca9a7e4-6d02-40e3-a129-0b2bf89de9b1", "member"), + JSONFactory700Organisations.organisationMemberJsonV700Example, + List($AuthenticatedUserIsRequired, InvalidJsonFormat, OrganisationNotFound, OrganisationAdminRequired, InvalidOrganisationMemberRole, + UserNotFoundById, OrganisationMemberAlreadyExists, UpdateOrganisationMemberError, UnknownError), + apiTagOrganisation :: Nil, + None, + http4sPartialFunction = Some(addMyOrganisationMember) + ) + + // Route: PUT /obp/v7.0.0/my/organisations/ORGANISATION_ID/members/USER_ID + lazy val updateMyOrganisationMember: Http4sRoute = Http4sRoute { + case req @ PUT -> `prefixPath` / "my" / "organisations" / organisationId / "members" / memberUserId => + EndpointHelpers.withUserAndBody[PutOrganisationMemberJsonV700, OrganisationMemberJsonV700](req) { (user, body, cc) => + for { + (_, membership) <- membershipOf(organisationId, user.userId, cc) + _ <- requireAdmin(membership, cc) + _ <- Helper.booleanToFuture(InvalidOrganisationMemberRole, 400, Some(cc))(Organisations.ValidMemberRoles.contains(body.member_role)) + member <- Future(Organisations.getMember(organisationId, memberUserId)).map(unboxFullOrFail(_, Some(cc), OrganisationMemberNotFound, 404)) + demotesLastAdmin = member.memberRole == Organisations.RoleAdmin && body.member_role != Organisations.RoleAdmin && + Organisations.adminCount(organisationId) <= 1 + _ <- Helper.booleanToFuture(OrganisationNeedsAnAdmin, 400, Some(cc))(!demotesLastAdmin) + updated <- Future(Organisations.updateMemberRole(organisationId, memberUserId, body.member_role)) + .map(unboxFullOrFail(_, Some(cc), UpdateOrganisationMemberError, 400)) + } yield JSONFactory700Organisations.createMemberJson(updated, UserVend.users.vend.getUserByUserId(memberUserId).toOption) + } + } + + resourceDocs += ResourceDoc( + implementedInApiVersion, + nameOf(updateMyOrganisationMember), + "PUT", + "/my/organisations/ORGANISATION_ID/members/USER_ID", + "Update My Organisation Member", + s"""Change a member's member_role to admin or member. Only admins may. The last admin cannot be made a member. + | + |$organisationDescription + | + |Authentication is Required.""".stripMargin, + PutOrganisationMemberJsonV700("admin"), + JSONFactory700Organisations.organisationMemberJsonV700Example, + List($AuthenticatedUserIsRequired, InvalidJsonFormat, OrganisationNotFound, OrganisationAdminRequired, InvalidOrganisationMemberRole, + OrganisationMemberNotFound, OrganisationNeedsAnAdmin, UpdateOrganisationMemberError, UnknownError), + apiTagOrganisation :: Nil, + None, + http4sPartialFunction = Some(updateMyOrganisationMember) + ) + + // Route: DELETE /obp/v7.0.0/my/organisations/ORGANISATION_ID/members/USER_ID (204) + lazy val removeMyOrganisationMember: Http4sRoute = Http4sRoute { + case req @ DELETE -> `prefixPath` / "my" / "organisations" / organisationId / "members" / memberUserId => + EndpointHelpers.withUserDelete(req) { (user, cc) => + for { + (_, membership) <- membershipOf(organisationId, user.userId, cc) + // A member may leave on their own; removing anyone else takes an admin. + _ <- if (memberUserId == user.userId) Future.successful(()) else requireAdmin(membership, cc) + member <- Future(Organisations.getMember(organisationId, memberUserId)).map(unboxFullOrFail(_, Some(cc), OrganisationMemberNotFound, 404)) + removesLastAdmin = member.memberRole == Organisations.RoleAdmin && Organisations.adminCount(organisationId) <= 1 + _ <- Helper.booleanToFuture(OrganisationNeedsAnAdmin, 400, Some(cc))(!removesLastAdmin) + _ <- Future(Organisations.removeMember(organisationId, memberUserId)).map(unboxFullOrFail(_, Some(cc), UpdateOrganisationMemberError, 400)) + } yield () + } + } + + resourceDocs += ResourceDoc( + implementedInApiVersion, + nameOf(removeMyOrganisationMember), + "DELETE", + "/my/organisations/ORGANISATION_ID/members/USER_ID", + "Remove My Organisation Member", + s"""Remove a member from one of your Organisations. Admins may remove anyone; any member may remove + |themselves to leave. The last admin cannot be removed. + | + |$organisationDescription + | + |Authentication is Required.""".stripMargin, + EmptyBody, + EmptyBody, + List($AuthenticatedUserIsRequired, OrganisationNotFound, OrganisationAdminRequired, OrganisationMemberNotFound, + OrganisationNeedsAnAdmin, UpdateOrganisationMemberError, UnknownError), + apiTagOrganisation :: Nil, + None, + http4sPartialFunction = Some(removeMyOrganisationMember) + ) + + // ─── Staff ─────────────────────────────────────────────────────────────── + // Their Roles are held at the Organisation's bank_id (a bank, or SYS), which is not in the path, so the docs + // declare the Roles for the catalogue and the handlers check them. + + // Route: POST /obp/v7.0.0/management/organisations (201) + lazy val createOrganisation: Http4sRoute = Http4sRoute { + case req @ POST -> `prefixPath` / "management" / "organisations" => + EndpointHelpers.withUserAndBodyCreated[PostManagementOrganisationJsonV700, OrganisationJsonV700](req) { (user, body, cc) => + for { + _ <- Helper.booleanToFuture(InvalidOrganisationName, 400, Some(cc))(validName(Option(body.name).getOrElse(""))) + bankId <- organisationBankId(body.bank_id, cc) + _ <- staffRoleCheck(bankId, user.userId, canCreateOrganisationAtOneBank, cc) + (firstAdmin, _) <- NewStyle.function.findByUserId(Option(body.admin_user_id).getOrElse(""), Some(cc)) + organisation <- Future { + Organisations.createOrganisation(bankId, body.name.trim, body.description.getOrElse(""), body.website, firstAdmin.userId, user.userId) + }.map(unboxFullOrFail(_, Some(cc), CreateOrganisationError, 400)) + } yield JSONFactory700Organisations.createOrganisationJson(organisation) + } + } + + resourceDocs += ResourceDoc( + implementedInApiVersion, + nameOf(createOrganisation), + "POST", + "/management/organisations", + "Create Organisation", + s"""Create an Organisation for someone else and name its first admin, for example when a regulator registers + |a participant. The Role is checked at the bank_id, which is SYS if left out. The first admin then adds the + |rest of their team. + | + |$organisationDescription + | + |Authentication is Required.""".stripMargin, + PostManagementOrganisationJsonV700(Some("SYS"), "Example Fintech Ltd", Some("Builds payment apps."), + Some("https://fintech.example.com"), "9ca9a7e4-6d02-40e3-a129-0b2bf89de9b1"), + JSONFactory700Organisations.organisationJsonV700Example, + List($AuthenticatedUserIsRequired, UserHasMissingRoles, InvalidJsonFormat, InvalidOrganisationName, InvalidOrganisationBankId, + UserNotFoundById, CreateOrganisationError, UnknownError), + apiTagOrganisation :: Nil, + Some(List(canCreateOrganisationAtOneBank)), + http4sPartialFunction = Some(createOrganisation) + ).disableAutoValidateRoles() + + // Route: GET /obp/v7.0.0/management/organisations + lazy val getOrganisations: Http4sRoute = Http4sRoute { + case req @ GET -> `prefixPath` / "management" / "organisations" => + EndpointHelpers.withUser(req) { (user, cc) => + val bankIdFilter = req.uri.query.params.get("bank_id").map(_.trim).filter(_.nonEmpty) + for { + organisations <- Future(Organisations.getOrganisations().filter(organisation => bankIdFilter.forall(_ == organisation.bankId))) + allowedBankIds = organisations.map(_.bankId).distinct + .filter(bankId => holdsAt(bankId, user.userId, canGetOrganisationAtOneBank, cc)).toSet + // With a bank_id, the Role must be held there. Without one, the list is filtered to the banks where it is held. + _ <- bankIdFilter match { + case Some(bankId) => staffRoleCheck(bankId, user.userId, canGetOrganisationAtOneBank, cc) + case None => Helper.booleanToFuture(s"$UserHasMissingRoles$canGetOrganisationAtOneBank at any bank_id.", 403, Some(cc)) { + allowedBankIds.nonEmpty || holdsAnywhere(user.userId, canGetOrganisationAtOneBank, cc) + } + } + } yield JSONFactory700Organisations.createOrganisationsJson(organisations.filter(organisation => allowedBankIds.contains(organisation.bankId))) + } + } + + resourceDocs += ResourceDoc( + implementedInApiVersion, + nameOf(getOrganisations), + "GET", + "/management/organisations", + "Get Organisations", + s"""Get the Organisations at the bank_ids where you hold CanGetOrganisationAtOneBank. With the query + |parameter bank_id, only those at that bank_id; the Role must then be held there. + | + |$organisationDescription + | + |Authentication is Required.""".stripMargin, + EmptyBody, + OrganisationsJsonV700(List(JSONFactory700Organisations.organisationJsonV700Example)), + List($AuthenticatedUserIsRequired, UserHasMissingRoles, UnknownError), + apiTagOrganisation :: Nil, + Some(List(canGetOrganisationAtOneBank)), + http4sPartialFunction = Some(getOrganisations) + ).disableAutoValidateRoles() + + // Route: GET /obp/v7.0.0/management/organisations/ORGANISATION_ID + lazy val getOrganisation: Http4sRoute = Http4sRoute { + case req @ GET -> `prefixPath` / "management" / "organisations" / organisationId => + EndpointHelpers.withUser(req) { (user, cc) => + staffOrganisation(organisationId, user.userId, canGetOrganisationAtOneBank, cc).map(JSONFactory700Organisations.createOrganisationJson) + } + } + + resourceDocs += ResourceDoc( + implementedInApiVersion, + nameOf(getOrganisation), + "GET", + "/management/organisations/ORGANISATION_ID", + "Get Organisation", + s"""Get an Organisation. The Role is checked at the Organisation's bank_id. + | + |$organisationDescription + | + |Authentication is Required.""".stripMargin, + EmptyBody, + JSONFactory700Organisations.organisationJsonV700Example, + List($AuthenticatedUserIsRequired, UserHasMissingRoles, OrganisationNotFound, UnknownError), + apiTagOrganisation :: Nil, + Some(List(canGetOrganisationAtOneBank)), + http4sPartialFunction = Some(getOrganisation) + ).disableAutoValidateRoles() + + // Route: GET /obp/v7.0.0/management/organisations/ORGANISATION_ID/members + lazy val getOrganisationMembers: Http4sRoute = Http4sRoute { + case req @ GET -> `prefixPath` / "management" / "organisations" / organisationId / "members" => + EndpointHelpers.withUser(req) { (user, cc) => + for { + organisation <- staffOrganisation(organisationId, user.userId, canGetOrganisationAtOneBank, cc) + members <- membersJson(organisation.organisationId) + } yield members + } + } + + resourceDocs += ResourceDoc( + implementedInApiVersion, + nameOf(getOrganisationMembers), + "GET", + "/management/organisations/ORGANISATION_ID/members", + "Get Organisation Members", + s"""Get the members of an Organisation, with their member_role. The Role is checked at the Organisation's + |bank_id. An application can use this to give the members access of its own, for example Roles in a space. + | + |$organisationDescription + | + |Authentication is Required.""".stripMargin, + EmptyBody, + OrganisationMembersJsonV700(List(JSONFactory700Organisations.organisationMemberJsonV700Example)), + List($AuthenticatedUserIsRequired, UserHasMissingRoles, OrganisationNotFound, UnknownError), + apiTagOrganisation :: Nil, + Some(List(canGetOrganisationAtOneBank)), + http4sPartialFunction = Some(getOrganisationMembers) + ).disableAutoValidateRoles() + + // Route: PUT /obp/v7.0.0/management/organisations/ORGANISATION_ID/status + lazy val updateOrganisationStatus: Http4sRoute = Http4sRoute { + case req @ PUT -> `prefixPath` / "management" / "organisations" / organisationId / "status" => + EndpointHelpers.withUserAndBody[PutOrganisationStatusJsonV700, OrganisationJsonV700](req) { (user, body, cc) => + for { + _ <- staffOrganisation(organisationId, user.userId, canUpdateOrganisationStatusAtOneBank, cc) + _ <- Helper.booleanToFuture(InvalidOrganisationStatus, 400, Some(cc))(Organisations.ValidStatuses.contains(body.status)) + updated <- Future(Organisations.updateStatus(organisationId, body.status)).map(unboxFullOrFail(_, Some(cc), UpdateOrganisationError, 400)) + } yield JSONFactory700Organisations.createOrganisationJson(updated) + } + } + + resourceDocs += ResourceDoc( + implementedInApiVersion, + nameOf(updateOrganisationStatus), + "PUT", + "/management/organisations/ORGANISATION_ID/status", + "Update Organisation Status", + s"""Set an Organisation to active or suspended. While it is suspended its members still see it, but they + |cannot act for its Consumers. The Role is checked at the Organisation's bank_id. + | + |$organisationDescription + | + |Authentication is Required.""".stripMargin, + PutOrganisationStatusJsonV700("suspended"), + JSONFactory700Organisations.organisationJsonV700Example, + List($AuthenticatedUserIsRequired, UserHasMissingRoles, InvalidJsonFormat, InvalidOrganisationStatus, OrganisationNotFound, + UpdateOrganisationError, UnknownError), + apiTagOrganisation :: Nil, + Some(List(canUpdateOrganisationStatusAtOneBank)), + http4sPartialFunction = Some(updateOrganisationStatus) + ).disableAutoValidateRoles() + + // ─── The caller's Consumers ────────────────────────────────────────────── + + // Route: GET /obp/v7.0.0/my/consumers + lazy val getMyConsumers: Http4sRoute = Http4sRoute { + case req @ GET -> `prefixPath` / "my" / "consumers" => + EndpointHelpers.withUser(req) { (user, _) => + ConsumerOwnership.consumersFor(user.userId) + .map(consumers => MyConsumersJsonV700(consumers.map(JSONFactory700Organisations.createMyConsumerJson))) + } + } + + resourceDocs += ResourceDoc( + implementedInApiVersion, + nameOf(getMyConsumers), + "GET", + "/my/consumers", + "Get My Consumers", + s"""Get the Consumers you may act for. These are the ones you created that belong to no Organisation, and + |those of the active Organisations you are a member of. No Role is needed. + | + |$consumerOwnerDescription""".stripMargin, + EmptyBody, + MyConsumersJsonV700(List(JSONFactory700Organisations.myConsumerJsonV700Example)), + List($AuthenticatedUserIsRequired, UnknownError), + apiTagConsumer :: apiTagOrganisation :: Nil, + None, + http4sPartialFunction = Some(getMyConsumers) + ) + + // Route: GET /obp/v7.0.0/my/consumers/CONSUMER_ID + lazy val getMyConsumer: Http4sRoute = Http4sRoute { + case req @ GET -> `prefixPath` / "my" / "consumers" / consumerId => + EndpointHelpers.withUser(req) { (user, cc) => + myConsumer(consumerId, user.userId, cc).map(JSONFactory700Organisations.createMyConsumerJson) + } + } + + resourceDocs += ResourceDoc( + implementedInApiVersion, + nameOf(getMyConsumer), + "GET", + "/my/consumers/CONSUMER_ID", + "Get My Consumer", + s"""Get one of your Consumers. A disabled Consumer is returned with enabled false, so you can see why your + |application stopped working. + | + |$consumerOwnerDescription""".stripMargin, + EmptyBody, + JSONFactory700Organisations.myConsumerJsonV700Example, + List($AuthenticatedUserIsRequired, MyConsumerNotFound, UnknownError), + apiTagConsumer :: apiTagOrganisation :: Nil, + None, + http4sPartialFunction = Some(getMyConsumer) + ) + + // Route: GET /obp/v7.0.0/my/consumers/CONSUMER_ID/usage + lazy val getMyConsumerUsage: Http4sRoute = Http4sRoute { + case req @ GET -> `prefixPath` / "my" / "consumers" / consumerId / "usage" => + EndpointHelpers.withUser(req) { (user, cc) => + for { + consumer <- myConsumer(consumerId, user.userId, cc) + callCounters <- Future(RateLimitingUtil.consumerRateLimitState(consumer.consumerId.get).toList) + date = new java.util.Date() + (activeRateLimit, rateLimitIds) <- RateLimitingUtil.getActiveRateLimitsWithIds(consumer.consumerId.get, date) + } yield MyConsumerUsageJsonV700( + consumer.consumerId.get, + JSONFactory600.createActiveRateLimitsJsonV600FromCallLimit(activeRateLimit, rateLimitIds, date), + JSONFactory600.createRedisCallCountersJson(callCounters) + ) + } + } + + resourceDocs += ResourceDoc( + implementedInApiVersion, + nameOf(getMyConsumerUsage), + "GET", + "/my/consumers/CONSUMER_ID/usage", + "Get My Consumer Usage", + s"""Get the rate limits one of your Consumers is under now, and how many calls it has made in each period + |so far. Every response from OBP also carries the headers X-Rate-Limit-Limit, X-Rate-Limit-Remaining and + |X-Rate-Limit-Reset for the calling application. + | + |$consumerOwnerDescription""".stripMargin, + EmptyBody, + JSONFactory700Organisations.myConsumerUsageJsonV700Example, + List($AuthenticatedUserIsRequired, MyConsumerNotFound, UnknownError), + apiTagConsumer :: apiTagOrganisation :: Nil, + None, + http4sPartialFunction = Some(getMyConsumerUsage) + ) + + // Route: GET /obp/v7.0.0/my/consumers/CONSUMER_ID/scopes + lazy val getMyConsumerScopes: Http4sRoute = Http4sRoute { + case req @ GET -> `prefixPath` / "my" / "consumers" / consumerId / "scopes" => + EndpointHelpers.withUser(req) { (user, cc) => + for { + consumer <- myConsumer(consumerId, user.userId, cc) + scopes <- Future(code.scope.Scope.scope.vend.getScopesByConsumerId(consumer.id.get.toString).openOr(Nil)) + } yield MyConsumerScopesJsonV700(consumer.consumerId.get, + scopes.map(scope => MyConsumerScopeJsonV700(scope.roleName, scope.bankId)).sortBy(scope => (scope.role_name, scope.bank_id))) + } + } + + resourceDocs += ResourceDoc( + implementedInApiVersion, + nameOf(getMyConsumerScopes), + "GET", + "/my/consumers/CONSUMER_ID/scopes", + "Get My Consumer Scopes", + s"""Get the Scopes one of your Consumers holds: the Roles it may use when it acts as itself, and where. A + |bank_id of "" means a system Role. + | + |$consumerOwnerDescription""".stripMargin, + EmptyBody, + JSONFactory700Organisations.myConsumerScopesJsonV700Example, + List($AuthenticatedUserIsRequired, MyConsumerNotFound, UnknownError), + apiTagConsumer :: apiTagScope :: apiTagOrganisation :: Nil, + None, + http4sPartialFunction = Some(getMyConsumerScopes) + ) + + // Route: GET /obp/v7.0.0/my/consumers/CONSUMER_ID/api-product-subscriptions + lazy val getMyConsumerApiProductSubscriptions: Http4sRoute = Http4sRoute { + case req @ GET -> `prefixPath` / "my" / "consumers" / consumerId / "api-product-subscriptions" => + EndpointHelpers.withUser(req) { (user, cc) => + for { + consumer <- myConsumer(consumerId, user.userId, cc) + (subscriptions, _) <- NewStyle.function.getApiProductSubscriptionsByConsumerId(consumer.consumerId.get, Some(cc)) + withAttributes <- Future.sequence(subscriptions.map { subscription => + NewStyle.function.getApiProductSubscriptionAttributes(subscription.apiProductSubscriptionId, Some(cc)) + .map { case (attributes, _) => JSONFactory700.createApiProductSubscriptionJsonV700(subscription, Some(attributes)) } + }) + } yield JSONFactory700.ApiProductSubscriptionsJsonV700(withAttributes) + } + } + + resourceDocs += ResourceDoc( + implementedInApiVersion, + nameOf(getMyConsumerApiProductSubscriptions), + "GET", + "/my/consumers/CONSUMER_ID/api-product-subscriptions", + "Get My Consumer Api Product Subscriptions", + s"""Get the API Product Subscriptions of one of your Consumers, at every bank, with their attributes. + | + |$consumerOwnerDescription""".stripMargin, + EmptyBody, + JSONFactory700.apiProductSubscriptionsJsonV700Example, + List($AuthenticatedUserIsRequired, MyConsumerNotFound, UnknownError), + apiTagConsumer :: apiTagApiProductSubscription :: apiTagOrganisation :: Nil, + None, + http4sPartialFunction = Some(getMyConsumerApiProductSubscriptions) + ) + + // Route: PUT /obp/v7.0.0/my/consumers/CONSUMER_ID/organisation + lazy val updateMyConsumerOrganisation: Http4sRoute = Http4sRoute { + case req @ PUT -> `prefixPath` / "my" / "consumers" / consumerId / "organisation" => + EndpointHelpers.withUserAndBody[PutConsumerOrganisationJsonV700, MyConsumerJsonV700](req) { (user, body, cc) => + val targetOrganisationId = body.organisation_id.map(_.trim).filter(_.nonEmpty) + for { + consumer <- myConsumer(consumerId, user.userId, cc) + // Taking a Consumer out of its Organisation, or into another one, takes an admin of its Organisation. + _ <- Helper.booleanToFuture(OrganisationAdminRequired, 403, Some(cc)) { + ConsumerOwnership.organisationIdOf(consumer).forall(_ => ConsumerOwnership.isAdminOfConsumersOrganisation(consumer, user.userId)) + } + // Putting it into an Organisation takes an admin of that Organisation. + _ <- targetOrganisationId match { + case Some(organisationId) => + for { + (organisation, membership) <- membershipOf(organisationId, user.userId, cc) + _ <- requireAdmin(membership, cc) + _ <- Helper.booleanToFuture(InvalidOrganisationStatus, 400, Some(cc))(organisation.status == Organisations.StatusActive) + } yield () + case None => Future.successful(()) + } + updated <- Future { + net.liftweb.util.Helpers.tryo(consumer.organisationId(targetOrganisationId.getOrElse("")).saveMe()) + }.map(unboxFullOrFail(_, Some(cc), UpdateConsumerOrganisationError, 400)) + } yield JSONFactory700Organisations.createMyConsumerJson(updated) + } + } + + resourceDocs += ResourceDoc( + implementedInApiVersion, + nameOf(updateMyConsumerOrganisation), + "PUT", + "/my/consumers/CONSUMER_ID/organisation", + "Update My Consumer Organisation", + s"""Move one of your Consumers into an Organisation, or out of it with organisation_id null. + | + |Moving a Consumer into an Organisation needs you to be an admin of that Organisation, which must be + |active. A Consumer that already belongs to an Organisation can only be moved by an admin of it. Once a + |Consumer belongs to an Organisation, its members act for it, and its creator no longer does on their own. + |Moved out, it belongs to its creator again. + | + |$consumerOwnerDescription""".stripMargin, + PutConsumerOrganisationJsonV700(Some("8ca8a7e4-6d02-48e3-a029-0b2bf89de9f0")), + JSONFactory700Organisations.myConsumerJsonV700Example, + List($AuthenticatedUserIsRequired, InvalidJsonFormat, MyConsumerNotFound, OrganisationNotFound, OrganisationAdminRequired, + InvalidOrganisationStatus, UpdateConsumerOrganisationError, UnknownError), + apiTagConsumer :: apiTagOrganisation :: Nil, + None, + http4sPartialFunction = Some(updateMyConsumerOrganisation) + ) +} diff --git a/obp-api/src/main/scala/code/api/v7_0_0/JSONFactory700Organisations.scala b/obp-api/src/main/scala/code/api/v7_0_0/JSONFactory700Organisations.scala new file mode 100644 index 0000000000..754ebb0445 --- /dev/null +++ b/obp-api/src/main/scala/code/api/v7_0_0/JSONFactory700Organisations.scala @@ -0,0 +1,190 @@ +/** +Open Bank Project - API +Copyright (C) 2011-2026, TESOBE GmbH. + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +Email: contact@tesobe.com +TESOBE GmbH. +Osloer Strasse 16/17 +Berlin 13359, Germany + +This product includes software developed at +TESOBE (http://www.tesobe.com/) + + */ + +package code.api.v7_0_0 + +import code.api.util.APIUtil +import code.model.Consumer +import code.organisation.{ConsumerOwnership, OrganisationMemberTrait, OrganisationTrait} + +/** An Organisation you create for yourself is always at SYS, so there is no bank_id. */ +case class PostOrganisationJsonV700( + name: String, + description: Option[String], + website: Option[String] +) + +/** Staff create an Organisation and name its first admin, who need not be the caller. */ +case class PostManagementOrganisationJsonV700( + bank_id: Option[String], + name: String, + description: Option[String], + website: Option[String], + admin_user_id: String +) + +case class PutOrganisationJsonV700( + name: Option[String], + description: Option[String], + website: Option[String] +) + +case class PutOrganisationStatusJsonV700(status: String) + +case class OrganisationJsonV700( + organisation_id: String, + bank_id: String, + name: String, + description: String, + website: Option[String], + status: String, + created_by_user_id: String, + created_at: java.util.Date, + updated_at: java.util.Date +) + +case class OrganisationsJsonV700(organisations: List[OrganisationJsonV700]) + +/** One of the caller's Organisations, with the caller's role in it. */ +case class MyOrganisationJsonV700( + organisation_id: String, + bank_id: String, + name: String, + description: String, + website: Option[String], + status: String, + member_role: String, + created_by_user_id: String, + created_at: java.util.Date, + updated_at: java.util.Date +) + +case class MyOrganisationsJsonV700(organisations: List[MyOrganisationJsonV700]) + +case class PostOrganisationMemberJsonV700(user_id: String, member_role: String) + +case class PutOrganisationMemberJsonV700(member_role: String) + +case class OrganisationMemberJsonV700( + organisation_id: String, + user_id: String, + username: String, + provider: String, + member_role: String, + created_by_user_id: String, + created_at: java.util.Date +) + +case class OrganisationMembersJsonV700(members: List[OrganisationMemberJsonV700]) + +case class PutConsumerOrganisationJsonV700(organisation_id: Option[String]) + +/** A Consumer as its owner sees it. Never its consumer key or secret. */ +case class MyConsumerJsonV700( + consumer_id: String, + app_name: String, + app_type: String, + description: String, + developer_email: String, + company: String, + redirect_url: String, + logo_url: Option[String], + enabled: Boolean, + created_by_user_id: String, + organisation_id: Option[String], + created: java.util.Date +) + +case class MyConsumersJsonV700(consumers: List[MyConsumerJsonV700]) + +/** How much a Consumer has used, and the limits it is under now. */ +case class MyConsumerUsageJsonV700( + consumer_id: String, + active_rate_limits: code.api.v6_0_0.ActiveRateLimitsJsonV600, + call_counters: code.api.v6_0_0.RedisCallCountersJsonV600 +) + +case class MyConsumerScopeJsonV700(role_name: String, bank_id: String) + +case class MyConsumerScopesJsonV700(consumer_id: String, scopes: List[MyConsumerScopeJsonV700]) + +object JSONFactory700Organisations { + + def createOrganisationJson(organisation: OrganisationTrait): OrganisationJsonV700 = + OrganisationJsonV700(organisation.organisationId, organisation.bankId, organisation.name, organisation.description, organisation.website, + organisation.status, organisation.createdByUserId, organisation.createdAt, organisation.updatedAt) + + def createOrganisationsJson(organisations: List[OrganisationTrait]): OrganisationsJsonV700 = + OrganisationsJsonV700(organisations.map(createOrganisationJson)) + + def createMyOrganisationJson(organisation: OrganisationTrait, membership: OrganisationMemberTrait): MyOrganisationJsonV700 = + MyOrganisationJsonV700(organisation.organisationId, organisation.bankId, organisation.name, organisation.description, organisation.website, + organisation.status, membership.memberRole, organisation.createdByUserId, organisation.createdAt, organisation.updatedAt) + + def createMemberJson(member: OrganisationMemberTrait, user: Option[com.openbankproject.commons.model.User]): OrganisationMemberJsonV700 = + OrganisationMemberJsonV700(member.organisationId, member.userId, user.map(_.name).getOrElse(""), + user.map(_.provider).getOrElse(""), member.memberRole, member.createdByUserId, member.createdAt) + + def createMyConsumerJson(consumer: Consumer): MyConsumerJsonV700 = + MyConsumerJsonV700( + consumer_id = consumer.consumerId.get, + app_name = consumer.name.get, + app_type = consumer.appType.get, + description = Option(consumer.description.get).getOrElse(""), + developer_email = Option(consumer.developerEmail.get).getOrElse(""), + company = Option(consumer.company.get).getOrElse(""), + redirect_url = Option(consumer.redirectURL.get).getOrElse(""), + logo_url = Option(consumer.logoUrl.get).filter(_.nonEmpty), + enabled = consumer.isActive.get, + created_by_user_id = Option(consumer.createdByUserId.get).getOrElse(""), + organisation_id = ConsumerOwnership.organisationIdOf(consumer), + created = consumer.createdAt.get + ) + + private val exampleDate = APIUtil.DateWithDayExampleObject + + lazy val organisationJsonV700Example = OrganisationJsonV700("8ca8a7e4-6d02-48e3-a029-0b2bf89de9f0", "SYS", "Example Fintech Ltd", + "Builds payment apps.", Some("https://fintech.example.com"), "active", "9ca9a7e4-6d02-40e3-a129-0b2bf89de9b1", exampleDate, exampleDate) + + lazy val myOrganisationJsonV700Example = MyOrganisationJsonV700("8ca8a7e4-6d02-48e3-a029-0b2bf89de9f0", "SYS", "Example Fintech Ltd", + "Builds payment apps.", Some("https://fintech.example.com"), "active", "admin", "9ca9a7e4-6d02-40e3-a129-0b2bf89de9b1", exampleDate, exampleDate) + + lazy val organisationMemberJsonV700Example = OrganisationMemberJsonV700("8ca8a7e4-6d02-48e3-a029-0b2bf89de9f0", + "9ca9a7e4-6d02-40e3-a129-0b2bf89de9b1", "susan.uk.29@example.com", "https://oidc.example.com", "member", + "9ca9a7e4-6d02-40e3-a129-0b2bf89de9b1", exampleDate) + + lazy val myConsumerJsonV700Example = MyConsumerJsonV700("7uy8a7e4-6d02-40e3-a129-0b2bf89de8uh", "Example Payments App", "Confidential", + "Pays bills.", "dev@fintech.example.com", "Example Fintech Ltd", "https://app.fintech.example.com/callback", None, true, + "9ca9a7e4-6d02-40e3-a129-0b2bf89de9b1", Some("8ca8a7e4-6d02-48e3-a029-0b2bf89de9f0"), exampleDate) + + lazy val myConsumerUsageJsonV700Example = MyConsumerUsageJsonV700("7uy8a7e4-6d02-40e3-a129-0b2bf89de8uh", + code.api.ResourceDocs1_4_0.SwaggerDefinitionsJSON.activeRateLimitsJsonV600, + code.api.ResourceDocs1_4_0.SwaggerDefinitionsJSON.redisCallCountersJsonV600) + + lazy val myConsumerScopesJsonV700Example = MyConsumerScopesJsonV700("7uy8a7e4-6d02-40e3-a129-0b2bf89de8uh", + List(MyConsumerScopeJsonV700("CanGetCustomersAtOneBank", "gh.29.uk"))) +} diff --git a/obp-api/src/main/scala/code/dynamicEntity/DynamicDataAccessProvider.scala b/obp-api/src/main/scala/code/dynamicEntity/DynamicDataAccessProvider.scala index 38191a638d..24a80285de 100644 --- a/obp-api/src/main/scala/code/dynamicEntity/DynamicDataAccessProvider.scala +++ b/obp-api/src/main/scala/code/dynamicEntity/DynamicDataAccessProvider.scala @@ -63,6 +63,24 @@ trait DynamicDataAccessT { def bankId: Option[String] } +/** + * A grant on one record to an Organisation rather than to one User. Every active member of an active + * Organisation holds these permissions on the record. Membership is checked each time the record is + * used, so people who join the Organisation gain access and people who leave lose it, with no change + * to the grant itself. + */ +trait DynamicDataOrganisationAccessT { + def dynamicDataId: String + def organisationId: String + def canRead: Boolean + def canUpdate: Boolean + def canDelete: Boolean + def canGrant: Boolean + def grantedBy: String + def entityName: String + def bankId: Option[String] +} + trait DynamicDataAccessProvider { /** @@ -93,16 +111,43 @@ trait DynamicDataAccessProvider { /** All ACL rows for a single record (for the GET .../access listing). */ def getAccessForRow(bankId: Option[String], entityName: String, dynamicDataId: String): List[DynamicDataAccessT] - /** DynamicDataIds of the entity in this space that `userId` may read -- the get-all filter. */ + /** + * Upsert one grant to an Organisation on the named record. Its active members hold these + * permissions while the Organisation is active. + */ + def grantToOrganisation(bankId: Option[String], entityName: String, dynamicDataId: String, organisationId: String, + canRead: Boolean, canUpdate: Boolean, canDelete: Boolean, canGrant: Boolean, + grantedBy: String): Box[DynamicDataOrganisationAccessT] + + /** + * Remove the Organisation's grant on the named record. Grants that members made to other Users + * stay: each of those was made by a person, and revoking that person removes them. + * Returns the number of grants removed (0 or 1). + */ + def revokeOrganisation(bankId: Option[String], entityName: String, dynamicDataId: String, organisationId: String): Box[Int] + + /** The Organisation grants on a single record (for the GET .../access listing). */ + def getOrganisationAccessForRow(bankId: Option[String], entityName: String, dynamicDataId: String): List[DynamicDataOrganisationAccessT] + + /** Remove every grant made to the Organisation, on any record. Used when the Organisation is deleted. */ + def deleteAllForOrganisation(organisationId: String): Box[Boolean] + + /** + * DynamicDataIds of the entity in this space that `userId` may read -- the get-all filter. + * This includes records granted to an active Organisation the User belongs to. + */ def getReadableDynamicDataIds(bankId: Option[String], entityName: String, userId: String): List[String] - /** Does `userId` hold `permission` on the named record? */ + /** + * Does `userId` hold `permission` on the named record, through their own grant or through a grant to + * an active Organisation they belong to? + */ def allows(bankId: Option[String], entityName: String, dynamicDataId: String, userId: String, permission: DynamicDataAccessPermission): Boolean - /** Cascade on record delete: remove every ACL row for that record. */ + /** Cascade on record delete: remove every ACL row for that record, User and Organisation grants alike. */ def deleteAllForRow(bankId: Option[String], entityName: String, dynamicDataId: String): Box[Boolean] - /** Cascade on entity delete: remove every ACL row for the entity in this space. */ + /** Cascade on entity delete: remove every ACL row for the entity in this space, User and Organisation grants alike. */ def deleteAllForEntity(bankId: Option[String], entityName: String): Box[Boolean] } diff --git a/obp-api/src/main/scala/code/dynamicEntity/DynamicEntityProvider.scala b/obp-api/src/main/scala/code/dynamicEntity/DynamicEntityProvider.scala index 0074aa0bd0..a7805cdc7c 100644 --- a/obp-api/src/main/scala/code/dynamicEntity/DynamicEntityProvider.scala +++ b/obp-api/src/main/scala/code/dynamicEntity/DynamicEntityProvider.scala @@ -552,10 +552,12 @@ object DynamicEntityCommons extends Converter[DynamicEntityT, DynamicEntityCommo flagFields.forall(f => knownFlagFields.contains(f.name)), s"$DynamicEntityInstanceValidateFail Unknown flag fields. Allowed flags: ${knownFlagFields.mkString(", ")}. Current root objects: ${fields.map(_.name).mkString(", ")}" ) - // §8.3: useRowLevelAccess is a master switch — mutually exclusive with public/community access. + // §8.3: public access would show every record to anyone, so it cannot be combined with row-level access. + // Community access can: it needs the entity's Get Role, so it is how staff read every record while + // everyone else reads only the records shared with them. checkFormat( - !(useRowLevelAccessValue && (hasPublicAccessValue || hasCommunityAccessValue)), - s"$DynamicEntityInstanceValidateFail useRowLevelAccess cannot be combined with hasPublicAccess or hasCommunityAccess." + !(useRowLevelAccessValue && hasPublicAccessValue), + s"$DynamicEntityInstanceValidateFail useRowLevelAccess cannot be combined with hasPublicAccess." ) val JField(entityName, metadataJson) = entityFields.head diff --git a/obp-api/src/main/scala/code/dynamicEntity/MappedDynamicDataAccessProvider.scala b/obp-api/src/main/scala/code/dynamicEntity/MappedDynamicDataAccessProvider.scala index f84014e248..8c4ca35c71 100644 --- a/obp-api/src/main/scala/code/dynamicEntity/MappedDynamicDataAccessProvider.scala +++ b/obp-api/src/main/scala/code/dynamicEntity/MappedDynamicDataAccessProvider.scala @@ -28,6 +28,7 @@ TESOBE (http://www.tesobe.com/) package code.DynamicData import code.api.Constant.DYNAMIC_ENTITY_SYSTEM_LEVEL_BANK_ID +import code.organisation.Organisations import net.liftweb.common.Box import net.liftweb.mapper._ import net.liftweb.util.Helpers.tryo @@ -118,34 +119,103 @@ object MappedDynamicDataAccessProvider extends DynamicDataAccessProvider { override def getAccessForRow(bankId: Option[String], entityName: String, dynamicDataId: String): List[DynamicDataAccessT] = DynamicDataAccess.findAll(whereClauseBankOrSystemAndEntityAndDataId(bankId, entityName, dynamicDataId): _*) - override def getReadableDynamicDataIds(bankId: Option[String], entityName: String, userId: String): List[String] = - DynamicDataAccess.findAll( + override def getReadableDynamicDataIds(bankId: Option[String], entityName: String, userId: String): List[String] = { + val grantedToUser = DynamicDataAccess.findAll( By(DynamicDataAccess.BankId, storedBankId(bankId)), By(DynamicDataAccess.EntityName, entityName), By(DynamicDataAccess.UserId, userId), By(DynamicDataAccess.CanRead, true) ).map(_.DynamicDataId.get) + val organisationIds = activeOrganisationIdsOf(userId) + val grantedToOrganisations = + if (organisationIds.isEmpty) Nil + else DynamicDataOrganisationAccess.findAll( + By(DynamicDataOrganisationAccess.BankId, storedBankId(bankId)), + By(DynamicDataOrganisationAccess.EntityName, entityName), + ByList(DynamicDataOrganisationAccess.OrganisationId, organisationIds), + By(DynamicDataOrganisationAccess.CanRead, true) + ).map(_.DynamicDataId.get) + (grantedToUser ++ grantedToOrganisations).distinct + } + + /** The Organisations the User is a member of that are active. A suspended Organisation grants nothing. */ + private def activeOrganisationIdsOf(userId: String): List[String] = + Organisations.getOrganisationsOfUser(userId) + .collect { case (organisation, _) if organisation.status == Organisations.StatusActive => organisation.organisationId } override def allows(bankId: Option[String], entityName: String, dynamicDataId: String, userId: String, permission: DynamicDataAccessPermission): Boolean = { import DynamicDataAccessPermission._ - DynamicDataAccess.find( - (whereClauseBankOrSystemAndEntityAndDataId(bankId, entityName, dynamicDataId) :+ By(DynamicDataAccess.UserId, userId)): _* - ).map { row => + def holds(canRead: Boolean, canUpdate: Boolean, canDelete: Boolean, canGrant: Boolean): Boolean = permission match { - case Read => row.CanRead.get - case Update => row.CanUpdate.get - case Delete => row.CanDelete.get - case Grant => row.CanGrant.get + case Read => canRead + case Update => canUpdate + case Delete => canDelete + case Grant => canGrant } - }.getOrElse(false) + val allowedByUserGrant = DynamicDataAccess.find( + (whereClauseBankOrSystemAndEntityAndDataId(bankId, entityName, dynamicDataId) :+ By(DynamicDataAccess.UserId, userId)): _* + ).exists(row => holds(row.canRead, row.canUpdate, row.canDelete, row.canGrant)) + allowedByUserGrant || { + val organisationGrants = getOrganisationAccessForRow(bankId, entityName, dynamicDataId) + .filter(grant => holds(grant.canRead, grant.canUpdate, grant.canDelete, grant.canGrant)) + organisationGrants.nonEmpty && { + val organisationIds = activeOrganisationIdsOf(userId).toSet + organisationGrants.exists(grant => organisationIds.contains(grant.organisationId)) + } + } + } + + private def whereClauseOrganisationGrantsOfRecord(bankId: Option[String], entityName: String, dynamicDataId: String): List[QueryParam[DynamicDataOrganisationAccess]] = + List( + By(DynamicDataOrganisationAccess.BankId, storedBankId(bankId)), + By(DynamicDataOrganisationAccess.EntityName, entityName), + By(DynamicDataOrganisationAccess.DynamicDataId, dynamicDataId) + ) + + override def grantToOrganisation(bankId: Option[String], entityName: String, dynamicDataId: String, organisationId: String, + canRead: Boolean, canUpdate: Boolean, canDelete: Boolean, canGrant: Boolean, + grantedBy: String): Box[DynamicDataOrganisationAccessT] = tryo { + val row = DynamicDataOrganisationAccess.find( + (whereClauseOrganisationGrantsOfRecord(bankId, entityName, dynamicDataId) :+ By(DynamicDataOrganisationAccess.OrganisationId, organisationId)): _* + ).getOrElse( + DynamicDataOrganisationAccess.create + .BankId(storedBankId(bankId)) + .EntityName(entityName) + .DynamicDataId(dynamicDataId) + .OrganisationId(organisationId) + ) + row.CanRead(canRead) + .CanUpdate(canUpdate) + .CanDelete(canDelete) + .CanGrant(canGrant) + .GrantedBy(grantedBy) + .saveMe() + } + + override def revokeOrganisation(bankId: Option[String], entityName: String, dynamicDataId: String, organisationId: String): Box[Int] = tryo { + DynamicDataOrganisationAccess.findAll( + (whereClauseOrganisationGrantsOfRecord(bankId, entityName, dynamicDataId) :+ By(DynamicDataOrganisationAccess.OrganisationId, organisationId)): _* + ).map(_.delete_!).count(identity) + } + + override def getOrganisationAccessForRow(bankId: Option[String], entityName: String, dynamicDataId: String): List[DynamicDataOrganisationAccessT] = + DynamicDataOrganisationAccess.findAll(whereClauseOrganisationGrantsOfRecord(bankId, entityName, dynamicDataId): _*) + + override def deleteAllForOrganisation(organisationId: String): Box[Boolean] = tryo { + DynamicDataOrganisationAccess.bulkDelete_!!(By(DynamicDataOrganisationAccess.OrganisationId, organisationId)) } override def deleteAllForRow(bankId: Option[String], entityName: String, dynamicDataId: String): Box[Boolean] = tryo { + DynamicDataOrganisationAccess.findAll(whereClauseOrganisationGrantsOfRecord(bankId, entityName, dynamicDataId): _*).foreach(_.delete_!) DynamicDataAccess.findAll(whereClauseBankOrSystemAndEntityAndDataId(bankId, entityName, dynamicDataId): _*).forall(_.delete_!) } override def deleteAllForEntity(bankId: Option[String], entityName: String): Box[Boolean] = tryo { + DynamicDataOrganisationAccess.bulkDelete_!!( + By(DynamicDataOrganisationAccess.BankId, storedBankId(bankId)), + By(DynamicDataOrganisationAccess.EntityName, entityName) + ) DynamicDataAccess.findAll( By(DynamicDataAccess.BankId, storedBankId(bankId)), By(DynamicDataAccess.EntityName, entityName) @@ -190,3 +260,40 @@ object DynamicDataAccess extends DynamicDataAccess with LongKeyedMetaMapper[Dyna Index(DynamicDataId, GrantedBy) :: super.dbIndexes } + +/** + * A grant on one record to an Organisation. Kept in its own table rather than as a DynamicDataAccess row + * with an empty user id, so that the unique index of each table names exactly who the grant is for. + */ +class DynamicDataOrganisationAccess extends DynamicDataOrganisationAccessT with LongKeyedMapper[DynamicDataOrganisationAccess] with IdPK { + + override def getSingleton = DynamicDataOrganisationAccess + + object DynamicDataId extends MappedString(this, 255) + object OrganisationId extends MappedString(this, 36) + object CanRead extends MappedBoolean(this) + object CanUpdate extends MappedBoolean(this) + object CanDelete extends MappedBoolean(this) + object CanGrant extends MappedBoolean(this) + object GrantedBy extends MappedString(this, 255) + object EntityName extends MappedString(this, 255) + object BankId extends MappedString(this, 255) + + override def dynamicDataId: String = DynamicDataId.get + override def organisationId: String = OrganisationId.get + override def canRead: Boolean = CanRead.get + override def canUpdate: Boolean = CanUpdate.get + override def canDelete: Boolean = CanDelete.get + override def canGrant: Boolean = CanGrant.get + override def grantedBy: String = GrantedBy.get + override def entityName: String = EntityName.get + override def bankId: Option[String] = Option(BankId.get).filterNot(_ == DYNAMIC_ENTITY_SYSTEM_LEVEL_BANK_ID) +} + +object DynamicDataOrganisationAccess extends DynamicDataOrganisationAccess with LongKeyedMetaMapper[DynamicDataOrganisationAccess] { + override def dbIndexes = + // One grant per (space, entity, record, Organisation), in the same order as DynamicDataAccess's index. + UniqueIndex(BankId, EntityName, DynamicDataId, OrganisationId) :: + Index(OrganisationId, EntityName, BankId) :: + super.dbIndexes +} diff --git a/obp-api/src/main/scala/code/model/OAuth.scala b/obp-api/src/main/scala/code/model/OAuth.scala index 2ce9b5eddb..2b1e5f4da8 100644 --- a/obp-api/src/main/scala/code/model/OAuth.scala +++ b/obp-api/src/main/scala/code/model/OAuth.scala @@ -634,6 +634,11 @@ class Consumer extends LongKeyedMapper[Consumer] with CreatedUpdated{ override def validations = validUri(this) _ :: super.validations } object createdByUserId extends MappedString(this, 36) + // The Organisation that owns this Consumer, or empty for a personal Consumer owned by its creator alone. + // See code.organisation.ConsumerOwnership. + object organisationId extends MappedString(this, 36) { + override def defaultValue = "" + } object perSecondCallLimit extends MappedLong(this) { override def defaultValue: Long = APIUtil.getPropsAsLongValue("rate_limiting_per_second", -1) diff --git a/obp-api/src/main/scala/code/organisation/ConsumerOwnership.scala b/obp-api/src/main/scala/code/organisation/ConsumerOwnership.scala new file mode 100644 index 0000000000..2237009f54 --- /dev/null +++ b/obp-api/src/main/scala/code/organisation/ConsumerOwnership.scala @@ -0,0 +1,83 @@ +/** +Open Bank Project - API +Copyright (C) 2011-2026, TESOBE GmbH. + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +Email: contact@tesobe.com +TESOBE GmbH. +Osloer Strasse 16/17 +Berlin 13359, Germany + +This product includes software developed at +TESOBE (http://www.tesobe.com/) + + */ + +package code.organisation + +import code.model.Consumer +import com.openbankproject.commons.ExecutionContext.Implicits.global +import net.liftweb.mapper.{By, ByList} + +import scala.concurrent.Future + +/** + * Who may act for a Consumer without a Role. A personal Consumer (no Organisation) is owned by the User who + * created it. A Consumer that belongs to an Organisation is owned by the members of that Organisation while + * it is active, and no longer by its creator alone, so it stays with the team when someone leaves. + * This is the one check behind the /my/consumers/... endpoints and the developer's side of API Product + * Subscriptions. + */ +object ConsumerOwnership { + + /** The Organisation a Consumer belongs to, if any. */ + def organisationIdOf(consumer: Consumer): Option[String] = + Option(consumer.organisationId.get).map(_.trim).filter(_.nonEmpty) + + /** True if the User may act for the Consumer: see the description of this object. */ + def canActFor(consumer: Consumer, userId: String): Boolean = + organisationIdOf(consumer) match { + case Some(organisationId) => isActiveMember(organisationId, userId) + case None => Option(consumer.createdByUserId.get).contains(userId) + } + + /** True if the User is an admin of the Consumer's active Organisation. */ + def isAdminOfConsumersOrganisation(consumer: Consumer, userId: String): Boolean = + organisationIdOf(consumer).exists(organisationId => isActiveAdmin(organisationId, userId)) + + def isActiveMember(organisationId: String, userId: String): Boolean = + Organisations.getMember(organisationId, userId).isDefined && organisationIsActive(organisationId) + + def isActiveAdmin(organisationId: String, userId: String): Boolean = + Organisations.getMember(organisationId, userId).exists(_.memberRole == Organisations.RoleAdmin) && + organisationIsActive(organisationId) + + private def organisationIsActive(organisationId: String): Boolean = + Organisations.getOrganisation(organisationId).exists(_.status == Organisations.StatusActive) + + /** The Consumers the User may act for: their personal ones, and those of their active Organisations. */ + def consumersFor(userId: String): Future[List[Consumer]] = Future { + val created = Consumer.findAll(By(Consumer.createdByUserId, userId)).filter(organisationIdOf(_).isEmpty) + val organisationIds = Organisations.getOrganisationsOfUser(userId) + .collect { case (organisation, _) if organisation.status == Organisations.StatusActive => organisation.organisationId } + val ofOrganisations = + if (organisationIds.isEmpty) Nil else Consumer.findAll(ByList(Consumer.organisationId, organisationIds)) + (created ++ ofOrganisations).groupBy(_.consumerId.get).values.map(_.head).toList.sortBy(_.name.get.toLowerCase) + } + + /** The number of Consumers that belong to the Organisation. */ + def consumerCount(organisationId: String): Long = + Consumer.count(By(Consumer.organisationId, organisationId)) +} diff --git a/obp-api/src/main/scala/code/organisation/Organisation.scala b/obp-api/src/main/scala/code/organisation/Organisation.scala new file mode 100644 index 0000000000..38d6bebfa8 --- /dev/null +++ b/obp-api/src/main/scala/code/organisation/Organisation.scala @@ -0,0 +1,222 @@ +/** +Open Bank Project - API +Copyright (C) 2011-2026, TESOBE GmbH. + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +Email: contact@tesobe.com +TESOBE GmbH. +Osloer Strasse 16/17 +Berlin 13359, Germany + +This product includes software developed at +TESOBE (http://www.tesobe.com/) + + */ + +package code.organisation + +import code.api.util.APIUtil +import net.liftweb.common.Box +import net.liftweb.mapper._ +import net.liftweb.util.Helpers.tryo + +/** + * An Organisation is a group of people that uses the APIs and owns Consumers, for example a fintech. It has + * members, each an admin or a member. Its bank_id is the space that administers it: SYS unless a bank is + * given. It is not a legal relationship with that bank (that is a Customer), and it is not a Tenant (a customer + * of the operator of this instance). See todo/todo_organisations.md. + */ +trait OrganisationTrait { + def organisationId: String + def bankId: String + def name: String + def description: String + def website: Option[String] + def status: String + def createdByUserId: String + def createdAt: java.util.Date + def updatedAt: java.util.Date +} + +trait OrganisationMemberTrait { + def organisationId: String + def userId: String + def memberRole: String + def createdByUserId: String + def createdAt: java.util.Date +} + +object Organisations { + val StatusActive = "active" + val StatusSuspended = "suspended" + val ValidStatuses: Set[String] = Set(StatusActive, StatusSuspended) + + val RoleAdmin = "admin" + val RoleMember = "member" + val ValidMemberRoles: Set[String] = Set(RoleAdmin, RoleMember) + + /** Creates the Organisation with its first admin. The request's transaction covers both rows. */ + def createOrganisation(bankId: String, name: String, description: String, website: Option[String], firstAdminUserId: String, + createdByUserId: String): Box[OrganisationTrait] = + tryo { + { + val organisation = Organisation.create + .OrganisationId(APIUtil.generateUUID()) + .BankId(bankId) + .Name(name) + .Description(description) + .Website(website.getOrElse("")) + .Status(StatusActive) + .CreatedByUserId(createdByUserId) + .saveMe() + OrganisationMember.create + .OrganisationId(organisation.organisationId) + .UserId(firstAdminUserId) + .MemberRole(RoleAdmin) + .CreatedByUserId(createdByUserId) + .saveMe() + organisation + } + } + + def getOrganisation(organisationId: String): Box[OrganisationTrait] = + Organisation.find(By(Organisation.OrganisationId, organisationId)) + + def getOrganisations(): List[OrganisationTrait] = Organisation.findAll(OrderBy(Organisation.Name, Ascending)) + + def getOrganisationsOfUser(userId: String): List[(OrganisationTrait, OrganisationMemberTrait)] = { + val memberships = OrganisationMember.findAll(By(OrganisationMember.UserId, userId)) + memberships.flatMap(membership => getOrganisation(membership.organisationId).toList.map(organisation => (organisation, membership))) + .sortBy(_._1.name.toLowerCase) + } + + def updateOrganisation(organisationId: String, name: Option[String], description: Option[String], website: Option[String]): Box[OrganisationTrait] = + Organisation.find(By(Organisation.OrganisationId, organisationId)).flatMap { organisation => + tryo { + name.foreach(value => organisation.Name(value)) + description.foreach(value => organisation.Description(value)) + website.foreach(value => organisation.Website(value)) + organisation.LastUpdate(new java.util.Date()).saveMe() + } + } + + def updateStatus(organisationId: String, status: String): Box[OrganisationTrait] = + Organisation.find(By(Organisation.OrganisationId, organisationId)).flatMap { organisation => + tryo { organisation.Status(status).LastUpdate(new java.util.Date()).saveMe() } + } + + /** Deletes the Organisation and its memberships. The caller checks first that it has no Consumers. */ + def deleteOrganisation(organisationId: String): Box[Boolean] = + Organisation.find(By(Organisation.OrganisationId, organisationId)).flatMap { organisation => + tryo { + OrganisationMember.bulkDelete_!!(By(OrganisationMember.OrganisationId, organisationId)) + // Its grants on Dynamic Entity records go too, so a later Organisation can never inherit them. + code.DynamicData.DynamicDataAccessProvider.provider.vend.deleteAllForOrganisation(organisationId) + organisation.delete_! + } + } + + def getMembers(organisationId: String): List[OrganisationMemberTrait] = + OrganisationMember.findAll(By(OrganisationMember.OrganisationId, organisationId), OrderBy(OrganisationMember.CreationDate, Ascending)) + + def getMember(organisationId: String, userId: String): Box[OrganisationMemberTrait] = + OrganisationMember.find(By(OrganisationMember.OrganisationId, organisationId), By(OrganisationMember.UserId, userId)) + + def addMember(organisationId: String, userId: String, memberRole: String, createdByUserId: String): Box[OrganisationMemberTrait] = + tryo { + OrganisationMember.create + .OrganisationId(organisationId) + .UserId(userId) + .MemberRole(memberRole) + .CreatedByUserId(createdByUserId) + .saveMe() + } + + def updateMemberRole(organisationId: String, userId: String, memberRole: String): Box[OrganisationMemberTrait] = + OrganisationMember.find(By(OrganisationMember.OrganisationId, organisationId), By(OrganisationMember.UserId, userId)).flatMap { member => + tryo { member.MemberRole(memberRole).saveMe() } + } + + def removeMember(organisationId: String, userId: String): Box[Boolean] = + OrganisationMember.find(By(OrganisationMember.OrganisationId, organisationId), By(OrganisationMember.UserId, userId)).flatMap { member => + tryo { member.delete_! } + } + + def adminCount(organisationId: String): Long = + OrganisationMember.count(By(OrganisationMember.OrganisationId, organisationId), By(OrganisationMember.MemberRole, RoleAdmin)) +} + +class Organisation extends OrganisationTrait with LongKeyedMapper[Organisation] with IdPK { + + def getSingleton = Organisation + + object OrganisationId extends MappedString(this, 36) + // The space that administers the Organisation: a bank id, or SYS. Staff Roles are checked here. + object BankId extends MappedString(this, 255) { + override def defaultValue = code.api.Constant.DYNAMIC_ENTITY_SYSTEM_LEVEL_BANK_ID + } + object Name extends MappedString(this, 255) + object Description extends MappedText(this) + object Website extends MappedString(this, 1024) + object Status extends MappedString(this, 32) + object CreatedByUserId extends MappedString(this, 36) + object CreationDate extends MappedDateTime(this) { + override def defaultValue = new java.util.Date() + } + object LastUpdate extends MappedDateTime(this) { + override def defaultValue = new java.util.Date() + } + + override def organisationId: String = OrganisationId.get + override def bankId: String = BankId.get + override def name: String = Name.get + override def description: String = Option(Description.get).getOrElse("") + override def website: Option[String] = Option(Website.get).filter(_.nonEmpty) + override def status: String = Status.get + override def createdByUserId: String = CreatedByUserId.get + override def createdAt: java.util.Date = CreationDate.get + override def updatedAt: java.util.Date = LastUpdate.get +} + +object Organisation extends Organisation with LongKeyedMetaMapper[Organisation] { + // Not "Organisation": the table of that name, from before Organisations were renamed Tenants, may still + // exist with old rows in it. + override def dbTableName = "ObpOrganisation" + override def dbIndexes = UniqueIndex(OrganisationId) :: Index(BankId) :: super.dbIndexes +} + +class OrganisationMember extends OrganisationMemberTrait with LongKeyedMapper[OrganisationMember] with IdPK { + + def getSingleton = OrganisationMember + + object OrganisationId extends MappedString(this, 36) + object UserId extends MappedString(this, 36) + object MemberRole extends MappedString(this, 32) + object CreatedByUserId extends MappedString(this, 36) + object CreationDate extends MappedDateTime(this) { + override def defaultValue = new java.util.Date() + } + + override def organisationId: String = OrganisationId.get + override def userId: String = UserId.get + override def memberRole: String = MemberRole.get + override def createdByUserId: String = CreatedByUserId.get + override def createdAt: java.util.Date = CreationDate.get +} + +object OrganisationMember extends OrganisationMember with LongKeyedMetaMapper[OrganisationMember] { + override def dbTableName = "ObpOrganisationMember" + override def dbIndexes = UniqueIndex(OrganisationId, UserId) :: Index(UserId) :: super.dbIndexes +} diff --git a/obp-api/src/main/scala/code/users/UserReference.scala b/obp-api/src/main/scala/code/users/UserReference.scala index 5891ede390..f1eb133bf3 100644 --- a/obp-api/src/main/scala/code/users/UserReference.scala +++ b/obp-api/src/main/scala/code/users/UserReference.scala @@ -162,6 +162,8 @@ object UserReference { case object PlatformApp_MarkedByUserId extends UserReference(UseAuthenticatedUserId, "code.platformapp.PlatformApp", List("MarkedByUserId"), "audit: who marked the Consumer as a platform app") case object ConsumerAccountAccess_GrantedByUserId extends UserReference(UseAuthenticatedUserId, "code.consumeraccountaccess.ConsumerAccountAccess", List("GrantedByUserId"), "audit: who gave the Consumer access to the view, as Entitlement_GrantedByUserId") case object GroupMembership_CreatedByUserId extends UserReference(UseAuthenticatedUserId, "code.group.GroupMembership", List("CreatedByUserId"), "audit: who added the member, as Entitlement_GrantedByUserId") + case object OrganisationMember_CreatedByUserId extends UserReference(UseAuthenticatedUserId, "code.organisation.OrganisationMember", List("CreatedByUserId"), "audit: who added the member, as GroupMembership_CreatedByUserId") + case object DynamicDataOrganisationAccess_GrantedBy extends UserReference(UseAuthenticatedUserId, "code.DynamicData.DynamicDataOrganisationAccess", List("GrantedBy"), "audit: who shared the record with the Organisation, as DynamicDataAccess_GrantedBy") case object AssetStatusHistory_ChangedByUserId extends UserReference(UseAuthenticatedUserId, "code.asset.AssetStatusHistory", List("ChangedByUserId"), "audit: who changed the asset's status, the question a regulator asks") case object File_ScanStatusUpdatedByUserId extends UserReference(UseAuthenticatedUserId, "code.files.File", List("ScanStatusUpdatedByUserId"), "audit: who set the scan status, the scanner or the staff member who decided") case object RetentionPolicy_CreatedByUserId extends UserReference(UseAuthenticatedUserId, "code.retention.RetentionPolicy", List("CreatedByUserId"), "audit: who created the retention policy") @@ -212,6 +214,8 @@ object UserReference { case object Bank_CreatedByUserId extends UserReference(UseOnBehalfOfUserId , "code.model.dataAccess.MappedBank", List("CreatedByUserId"), "creator grant already resolved at the endpoint") case object SelfServiceBank_CreatedByUserId extends UserReference(UseOnBehalfOfUserId , "code.model.dataAccess.SelfServiceBank", List("CreatedByUserId"), "as Bank_CreatedByUserId; the Create My Bank quota counts these rows per creator") case object Tenant_CreatedByUserId extends UserReference(UseOnBehalfOfUserId , "code.tenant.Tenant", List("CreatedByUserId"), "outlives the Consent that created it") + case object Organisation_CreatedByUserId extends UserReference(UseOnBehalfOfUserId , "code.organisation.Organisation", List("CreatedByUserId"), "outlives the Consent that created it, as Tenant_CreatedByUserId") + case object OrganisationMember_UserId extends UserReference(UseOnBehalfOfUserId , "code.organisation.OrganisationMember", List("UserId"), "the member, who acts for the Organisation and its Consumers; as GroupMembership_UserId, a membership held by a consent user would die with its Consent") case object Asset_CreatedByUserId extends UserReference(UseOnBehalfOfUserId , "code.asset.Asset", List("CreatedByUserId"), "outlives the Consent that created it, as RoutingScheme_CreatedByUserId; seeded rows hold system:asset-seed") case object File_UserId extends UserReference(UseOnBehalfOfUserId , "code.files.File", List("UserId", "OnBehalfOfUserId"), "record both: UserId = who uploaded (the agent), OnBehalfOfUserId = the human, who owns the file") case object FileAttachment_UserId extends UserReference(UseOnBehalfOfUserId , "code.files.FileAttachment", List("UserId", "OnBehalfOfUserId"), "record both: UserId = who attached (the agent), OnBehalfOfUserId = the human") @@ -272,6 +276,8 @@ object UserReference { PlatformApp_MarkedByUserId, ConsumerAccountAccess_GrantedByUserId, GroupMembership_CreatedByUserId, + OrganisationMember_CreatedByUserId, + DynamicDataOrganisationAccess_GrantedBy, AssetStatusHistory_ChangedByUserId, RetentionPolicy_CreatedByUserId, RetentionHold_PlacedByUserId, @@ -317,6 +323,8 @@ object UserReference { Bank_CreatedByUserId, SelfServiceBank_CreatedByUserId, Tenant_CreatedByUserId, + Organisation_CreatedByUserId, + OrganisationMember_UserId, Asset_CreatedByUserId, File_UserId, File_ScanStatusUpdatedByUserId, @@ -417,6 +425,8 @@ object UserReference { ApiProductSubscription_CreatedByUserId -> mechanicalBatch, DynamicGlossaryItem_CreatedByUserId -> mechanicalBatch, Tenant_CreatedByUserId -> mechanicalBatch, + Organisation_CreatedByUserId -> mechanicalBatch, + OrganisationMember_UserId -> mechanicalBatch, SelfServiceBank_CreatedByUserId -> mechanicalBatch, PayeeLookup_CreatedByUserId -> mechanicalBatch, RoutingScheme_CreatedByUserId -> mechanicalBatch, diff --git a/obp-api/src/main/scala/deletion/DeleteBankCascade.scala b/obp-api/src/main/scala/deletion/DeleteBankCascade.scala index f05e330db6..5b55bc420c 100644 --- a/obp-api/src/main/scala/deletion/DeleteBankCascade.scala +++ b/obp-api/src/main/scala/deletion/DeleteBankCascade.scala @@ -103,6 +103,7 @@ object DeleteBankCascade { private def deleteRecordsWithoutDefinition(bankId: BankId): Boolean = { DynamicData.bulkDelete_!!(By(DynamicData.BankId, bankId.value)) DynamicDataAccess.bulkDelete_!!(By(DynamicDataAccess.BankId, bankId.value)) + code.DynamicData.DynamicDataOrganisationAccess.bulkDelete_!!(By(code.DynamicData.DynamicDataOrganisationAccess.BankId, bankId.value)) true } diff --git a/obp-api/src/test/scala/code/api/v4_0_0/AccountTest.scala b/obp-api/src/test/scala/code/api/v4_0_0/AccountTest.scala index 8b07de5182..acda464a00 100644 --- a/obp-api/src/test/scala/code/api/v4_0_0/AccountTest.scala +++ b/obp-api/src/test/scala/code/api/v4_0_0/AccountTest.scala @@ -431,6 +431,36 @@ class AccountTest extends V400ServerSetup { responseIncorrectBank.body.extract[ModeratedAccountsJSON400].accounts should be(List.empty) } + + // A user without the owner view of an account must not find it, nor learn its ids, through the regex. + scenario("Another user's account is not matched and its ids are not returned", ApiEndpoint6, VersionOfApi) { + Given("user1 creates an account with a routing address that only it can see") + val accountRoutingSchemeTest = "AccountNumber" + val uniquePrefix = "SENTINEL" + APIUtil.generateUUID().replace("-", "").take(12).toUpperCase + val createdAccountJson = SwaggerDefinitionsJSON.createAccountRequestJsonV310 + .copy(user_id = resourceUser1.userId, balance = AmountOfMoneyJsonV121("EUR", "0"), + account_routings = List(AccountRoutingJsonV121(accountRoutingSchemeTest, uniquePrefix + "-EUR"))) + val createdAccount = createAccountViaEndpoint(testBankId.value, createdAccountJson, user1) + val queryJson = getAccountByRoutingJson.copy(bank_id = None, + account_routing = AccountRoutingJsonV121(accountRoutingSchemeTest, "^" + uniquePrefix)) + + When("user2, who has no view on that account, queries with a regex that matches its address") + val request = (v4_0_0_Request / "management" / "accounts" / "account-routing-regex-query").POST <@ (user2) + val response = makePostRequest(request, write(queryJson)) + + Then("We should get a 200 with no accounts, and nothing about user1's account") + response.code should equal(200) + response.body.extract[ModeratedAccountsJSON400].accounts should be(List.empty) + response.body.toString.contains(createdAccount.account_id) should be(false) + + When("user1, who owns the account, makes the same query") + val requestOwner = (v4_0_0_Request / "management" / "accounts" / "account-routing-regex-query").POST <@ (user1) + val responseOwner = makePostRequest(requestOwner, write(queryJson)) + + Then("We should get a 200 with that account") + responseOwner.code should equal(200) + responseOwner.body.extract[ModeratedAccountsJSON400].accounts.map(_.id) should be(List(createdAccount.account_id)) + } } feature(s"test ${ApiEndpoint3.name}") { diff --git a/obp-api/src/test/scala/code/api/v6_0_0/ChatMessageEditTest.scala b/obp-api/src/test/scala/code/api/v6_0_0/ChatMessageEditTest.scala new file mode 100644 index 0000000000..d2c7c36937 --- /dev/null +++ b/obp-api/src/test/scala/code/api/v6_0_0/ChatMessageEditTest.scala @@ -0,0 +1,114 @@ +/** +Open Bank Project - API +Copyright (C) 2011-2026, TESOBE GmbH. + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +Email: contact@tesobe.com +TESOBE GmbH. +Osloer Strasse 16/17 +Berlin 13359, Germany + +This product includes software developed at +TESOBE (http://www.tesobe.com/) + + */ + +package code.api.v6_0_0 + +import code.api.util.APIUtil.OAuth._ +import code.api.util.ErrorMessages.{ChatMessageNotFound, ChatRoomNotFound} +import code.chat.{ChatMessageTrait, ChatRoomTrait, ParticipantTrait} +import com.openbankproject.commons.model.ErrorMessage +import com.openbankproject.commons.util.ApiVersion +import org.scalatest.Tag + +/** + * A message can only be edited through the room (and, for bank rooms, the bank) it belongs to. + */ +class ChatMessageEditTest extends V600ServerSetup { + + object VersionOfApi extends Tag(ApiVersion.v6_0_0.toString) + object ApiEndpointEditBank extends Tag("editBankChatMessage") + object ApiEndpointEditSystem extends Tag("editSystemChatMessage") + + private val newContentBody = """{"content":"changed text"}""" + + // a room at bankId that user1 is a participant of + private def createRoomWithUser1(bankId: String): String = { + val room = ChatRoomTrait.chatRoomProvider.vend.createChatRoom( + bankId, s"room-${java.util.UUID.randomUUID()}", "test room", resourceUser2.userId).openOrThrowException("room") + ParticipantTrait.participantProvider.vend.addParticipant( + room.chatRoomId, resourceUser1.userId, "", Nil, "").openOrThrowException("participant") + room.chatRoomId + } + + // a message by user1 in a room user1 is not in (as if user1 had been removed from it) + private def createOwnMessageInOtherRoom(bankId: String): String = { + val otherRoom = ChatRoomTrait.chatRoomProvider.vend.createChatRoom( + bankId, s"other-${java.util.UUID.randomUUID()}", "other room", resourceUser2.userId).openOrThrowException("room") + ChatMessageTrait.chatMessageProvider.vend.createMessage( + otherRoom.chatRoomId, resourceUser1.userId, "", "original text", "text", Nil, "", "").openOrThrowException("message").chatMessageId + } + + private def contentOf(chatMessageId: String): String = + ChatMessageTrait.chatMessageProvider.vend.getMessage(chatMessageId).map(_.content).openOr("") + + feature(s"Edit Bank Chat Message - PUT /obp/v6.0.0/banks/BANK_ID/chat-rooms/CHAT_ROOM_ID/messages/CHAT_MESSAGE_ID - $VersionOfApi") { + + scenario("A message of another room is refused with 404 and not changed", ApiEndpointEditBank, VersionOfApi) { + val roomId = createRoomWithUser1(testBankId1.value) + val messageId = createOwnMessageInOtherRoom(testBankId1.value) + val request = (v6_0_0_Request / "banks" / testBankId1.value / "chat-rooms" / roomId / "messages" / messageId).PUT <@ (user1) + val response = makePutRequest(request, newContentBody) + response.code should equal(404) + response.body.extract[ErrorMessage].message should equal(ChatMessageNotFound) + contentOf(messageId) should equal("original text") + } + + scenario("A room of another bank is refused with 404 and the message not changed", ApiEndpointEditBank, VersionOfApi) { + val roomId = createRoomWithUser1(testBankId1.value) + val messageId = ChatMessageTrait.chatMessageProvider.vend.createMessage( + roomId, resourceUser1.userId, "", "original text", "text", Nil, "", "").openOrThrowException("message").chatMessageId + val request = (v6_0_0_Request / "banks" / testBankId2.value / "chat-rooms" / roomId / "messages" / messageId).PUT <@ (user1) + val response = makePutRequest(request, newContentBody) + response.code should equal(404) + response.body.extract[ErrorMessage].message should equal(ChatRoomNotFound) + contentOf(messageId) should equal("original text") + } + + scenario("A message of the room in the path is edited with 200", ApiEndpointEditBank, VersionOfApi) { + val roomId = createRoomWithUser1(testBankId1.value) + val messageId = ChatMessageTrait.chatMessageProvider.vend.createMessage( + roomId, resourceUser1.userId, "", "original text", "text", Nil, "", "").openOrThrowException("message").chatMessageId + val request = (v6_0_0_Request / "banks" / testBankId1.value / "chat-rooms" / roomId / "messages" / messageId).PUT <@ (user1) + val response = makePutRequest(request, newContentBody) + response.code should equal(200) + contentOf(messageId) should equal("changed text") + } + } + + feature(s"Edit System Chat Message - PUT /obp/v6.0.0/chat-rooms/CHAT_ROOM_ID/messages/CHAT_MESSAGE_ID - $VersionOfApi") { + + scenario("A message of another room is refused with 404 and not changed", ApiEndpointEditSystem, VersionOfApi) { + val roomId = createRoomWithUser1("") + val messageId = createOwnMessageInOtherRoom("") + val request = (v6_0_0_Request / "chat-rooms" / roomId / "messages" / messageId).PUT <@ (user1) + val response = makePutRequest(request, newContentBody) + response.code should equal(404) + response.body.extract[ErrorMessage].message should equal(ChatMessageNotFound) + contentOf(messageId) should equal("original text") + } + } +} diff --git a/obp-api/src/test/scala/code/api/v6_0_0/DynamicEntityJoinQueryIntegrationTest.scala b/obp-api/src/test/scala/code/api/v6_0_0/DynamicEntityJoinQueryIntegrationTest.scala index 22a0d9ebf4..ce4634a46e 100644 --- a/obp-api/src/test/scala/code/api/v6_0_0/DynamicEntityJoinQueryIntegrationTest.scala +++ b/obp-api/src/test/scala/code/api/v6_0_0/DynamicEntityJoinQueryIntegrationTest.scala @@ -116,7 +116,7 @@ class DynamicEntityJoinQueryIntegrationTest extends V600ServerSetup { saveRec(Contract, "active" -> JBool(false)) // orphan: partner_ref absent (NULL) val d1 = saveRec(Deal, "partner_ref" -> JString(p1)) - saveRec(Deal, "partner_ref" -> JString(p2)) // d2: granted to nobody + val d2 = saveRec(Deal, "partner_ref" -> JString(p2)) // granted to no User; shared with an Organisation below DynamicDataAccessProvider.provider.vend.grant(bankId = None, entityName = Deal, dynamicDataId = d1, userId = userA, canRead = true, canUpdate = false, canDelete = false, canGrant = false, grantedBy = owner) @@ -147,6 +147,18 @@ class DynamicEntityJoinQueryIntegrationTest extends V600ServerSetup { queryPartnerIds(dealExists, userA) shouldBe Set(p1) // userB has no grants -> no readable deals -> no partner matches. queryPartnerIds(dealExists, userB) shouldBe Set.empty[String] + + // D2 is shared with an Organisation userB belongs to -> P2 counts for userB, while the Organisation is active. + val organisationId = code.organisation.Organisations + .createOrganisation(code.api.Constant.DYNAMIC_ENTITY_SYSTEM_LEVEL_BANK_ID, s"Join team $sfx", "", None, userB, owner) + .openOrThrowException("the Organisation should be created").organisationId + DynamicDataAccessProvider.provider.vend.grantToOrganisation(bankId = None, entityName = Deal, dynamicDataId = d2, + organisationId = organisationId, canRead = true, canUpdate = false, canDelete = false, canGrant = false, + grantedBy = owner) + queryPartnerIds(dealExists, userB) shouldBe Set(p2) + code.organisation.Organisations.updateStatus(organisationId, code.organisation.Organisations.StatusSuspended) + queryPartnerIds(dealExists, userB) shouldBe Set.empty[String] + code.organisation.Organisations.deleteOrganisation(organisationId) } scenario("indexing is switched on for entities that already have rows, then a join works (backfill)") { diff --git a/obp-api/src/test/scala/code/api/v6_0_0/DynamicEntityRowLevelAccessTest.scala b/obp-api/src/test/scala/code/api/v6_0_0/DynamicEntityRowLevelAccessTest.scala index a37e546316..5e61f693c4 100644 --- a/obp-api/src/test/scala/code/api/v6_0_0/DynamicEntityRowLevelAccessTest.scala +++ b/obp-api/src/test/scala/code/api/v6_0_0/DynamicEntityRowLevelAccessTest.scala @@ -40,7 +40,7 @@ import code.api.Constant.DYNAMIC_ENTITY_SYSTEM_LEVEL_BANK_ID * Row-level access (use_row_level_access) — see ideas/DYNAMIC_ENTITY_ROW_LEVEL_ACCESS.md. * Covers: owner bootstrap, per-row read isolation (404 hides), owner sharing with no role, * per-row update gate (403), revoke cascade, get-all ACL filter, admin-role override, - * flag-off 400, and the §8.3 public/community mutual-exclusion guard. + * flag-off 400, the §8.3 public-access guard, community reads with the Get role, and Organisation grants. */ class DynamicEntityRowLevelAccessTest extends V600ServerSetup { @@ -208,7 +208,7 @@ class DynamicEntityRowLevelAccessTest extends V600ServerSetup { // ==================== Feature 5: flag-off & definition-time validation ==================== - feature("Feature 5: flag-off and mutual-exclusion validation") { + feature("Feature 5: flag-off and flag-combination validation") { scenario("5.1: access endpoints return 400 for a non-row-level entity", VersionOfApi) { val normalEntity: JValue = ("entity_name" -> "test_normal_rl") ~ ("has_personal_entity" -> false) ~ ("schema" -> simpleSchema) @@ -238,6 +238,39 @@ class DynamicEntityRowLevelAccessTest extends V600ServerSetup { Then("it is rejected (not 201)") code should equal(400) } + + scenario("5.3: use_row_level_access with has_community_access lets the Get role read every record", VersionOfApi) { + val rowLevelWithCommunity: JValue = + ("entity_name" -> "test_rl_community") ~ + ("use_row_level_access" -> true) ~ + ("has_community_access" -> true) ~ + ("schema" -> simpleSchema) + val (createStatus, body) = createSystemEntity(rowLevelWithCommunity) + Then("the entity is created") + createStatus should equal(201) + val dynamicEntityId = (body \ "dynamic_entity_id").extract[String] + try { + val createResponse = makePostRequest((dynamicEntity_Request / "test_rl_community").POST <@ (user1), write(("name" -> "private to user1"): JValue)) + createResponse.code should equal(201) + val recordId = (createResponse.body \ "test_rl_community" \ "test_rl_community_id").extract[String] + + When("user2, with no grant and no role, reads the record and the community list") + Then("the record is hidden and the community list is refused") + makeGetRequest((dynamicEntity_Request / "test_rl_community" / recordId).GET <@ (user2)).code should equal(404) + val refusedCommunityList = makeGetRequest((dynamicEntity_Request / "community" / "test_rl_community").GET <@ (user2)) + refusedCommunityList.code should equal(403) + refusedCommunityList.body.toString should include("CanGetDynamicEntityRecord_test_rl_community") + + When("user2 is given the entity's Get role") + Entitlement.entitlement.vend.addEntitlement(DYNAMIC_ENTITY_SYSTEM_LEVEL_BANK_ID, resourceUser2.userId, "CanGetDynamicEntityRecord_test_rl_community") + Then("user2 reads every record through the community URL") + val communityList = makeGetRequest((dynamicEntity_Request / "community" / "test_rl_community").GET <@ (user2)) + communityList.code should equal(200) + (communityList.body \ "test_rl_community_list").asInstanceOf[JArray].arr.size should equal(1) + And("the role still does not open the record through the shared URL, where the access list decides") + makeGetRequest((dynamicEntity_Request / "test_rl_community" / recordId).GET <@ (user2)).code should equal(404) + } finally deleteSystemEntity(dynamicEntityId) + } } // ==================== Feature 6: a row-level record keeps its id through updates ==================== @@ -308,4 +341,120 @@ class DynamicEntityRowLevelAccessTest extends V600ServerSetup { } } + // ==================== Feature 7: sharing with an Organisation ==================== + + // user1 creates the Organisation and is its admin; user2 is a member; user3 belongs to nothing. + private def createOrganisationWithMember(memberUserId: String): String = { + val organisationId = code.organisation.Organisations.createOrganisation( + DYNAMIC_ENTITY_SYSTEM_LEVEL_BANK_ID, "Row access team", "", None, resourceUser1.userId, resourceUser1.userId + ).openOrThrowException("the Organisation should be created").organisationId + code.organisation.Organisations.addMember(organisationId, memberUserId, code.organisation.Organisations.RoleMember, resourceUser1.userId) + .openOrThrowException("the member should be added") + organisationId + } + + private def grantToOrganisation(recordId: String, organisationId: String, canUpdate: Boolean) = + makePutRequest( + (dynamicEntity_Request / "test_rl" / recordId / "access").PUT <@ (user1), + write(("organisation_id" -> organisationId) ~ ("can_read" -> true) ~ ("can_update" -> canUpdate))) + + feature("Feature 7: a grant to an Organisation follows its membership") { + scenario("7.1: members read and update; outsiders, former members and suspended Organisations do not", VersionOfApi) { + val (createStatus, body) = createSystemEntity(entityRowLevel) + createStatus should equal(201) + val dynamicEntityId = (body \ "dynamic_entity_id").extract[String] + val organisationId = createOrganisationWithMember(resourceUser2.userId) + try { + val recordId = createRecord("team answer") + + When("user1 grants read and update to the Organisation") + val grantResponse = grantToOrganisation(recordId, organisationId, canUpdate = true) + grantResponse.code should equal(200) + Then("the access list shows the grant under organisation_access, with can_grant false by default") + val organisationGrant = (grantResponse.body \ "organisation_access").asInstanceOf[JArray].arr.head + (organisationGrant \ "organisation_id").extract[String] should equal(organisationId) + (organisationGrant \ "can_grant").extract[Boolean] should equal(false) + + Then("user2, a member, reads, lists and updates the record") + makeGetRequest((dynamicEntity_Request / "test_rl" / recordId).GET <@ (user2)).code should equal(200) + val memberList = makeGetRequest((dynamicEntity_Request / "test_rl").GET <@ (user2)) + (memberList.body \ "test_rl_list").asInstanceOf[JArray].arr.size should equal(1) + makePutRequest((dynamicEntity_Request / "test_rl" / recordId).PUT <@ (user2), write(("name" -> "edited by the team"): JValue)) + .code should equal(200) + + And("user2 cannot change the access list, because the Organisation has no can_grant") + makePutRequest( + (dynamicEntity_Request / "test_rl" / recordId / "access").PUT <@ (user2), + write(("user_id" -> resourceUser3.userId) ~ ("can_read" -> true))).code should equal(403) + + And("user3, who is not a member, gets 404") + makeGetRequest((dynamicEntity_Request / "test_rl" / recordId).GET <@ (user3)).code should equal(404) + + When("the Organisation is suspended") + code_organisation.updateStatus(organisationId, code_organisation.StatusSuspended) + Then("user2 loses access") + makeGetRequest((dynamicEntity_Request / "test_rl" / recordId).GET <@ (user2)).code should equal(404) + code_organisation.updateStatus(organisationId, code_organisation.StatusActive) + makeGetRequest((dynamicEntity_Request / "test_rl" / recordId).GET <@ (user2)).code should equal(200) + + When("user2 leaves the Organisation") + code_organisation.removeMember(organisationId, resourceUser2.userId) + Then("user2 loses access, with no change to the grant") + makeGetRequest((dynamicEntity_Request / "test_rl" / recordId).GET <@ (user2)).code should equal(404) + + When("user3 joins the Organisation") + code_organisation.addMember(organisationId, resourceUser3.userId, code_organisation.RoleMember, resourceUser1.userId) + Then("user3 gains access") + makeGetRequest((dynamicEntity_Request / "test_rl" / recordId).GET <@ (user3)).code should equal(200) + + When("user1 revokes the Organisation") + val revokeResponse = makeDeleteRequest( + (dynamicEntity_Request / "test_rl" / recordId / "access" / "organisations" / organisationId).DELETE <@ (user1)) + revokeResponse.code should equal(200) + (revokeResponse.body \ "revoked_count").extract[Int] should equal(1) + Then("its members lose access, and the creator keeps theirs") + makeGetRequest((dynamicEntity_Request / "test_rl" / recordId).GET <@ (user3)).code should equal(404) + makeGetRequest((dynamicEntity_Request / "test_rl" / recordId).GET <@ (user1)).code should equal(200) + } finally { + deleteSystemEntity(dynamicEntityId) + code_organisation.deleteOrganisation(organisationId) + } + } + + scenario("7.2: an entry must name a User or an Organisation that exists", VersionOfApi) { + val (createStatus, body) = createSystemEntity(entityRowLevel) + createStatus should equal(201) + val dynamicEntityId = (body \ "dynamic_entity_id").extract[String] + val organisationId = createOrganisationWithMember(resourceUser2.userId) + try { + val recordId = createRecord("checked entries") + + When("an entry names both a user_id and an organisation_id") + val bothResponse = makePutRequest( + (dynamicEntity_Request / "test_rl" / recordId / "access").PUT <@ (user1), + write(("user_id" -> resourceUser2.userId) ~ ("organisation_id" -> organisationId) ~ ("can_read" -> true))) + Then("it is 400") + bothResponse.code should equal(400) + bothResponse.body.toString should include(code.api.util.ErrorMessages.InvalidRecordAccessEntry.takeWhile(_ != ':')) + + When("an entry names an Organisation that does not exist") + val unknownResponse = grantToOrganisation(recordId, "no-such-organisation", canUpdate = false) + Then("it is 404") + unknownResponse.code should equal(404) + unknownResponse.body.toString should include(code.api.util.ErrorMessages.RecordAccessOrganisationNotFound.takeWhile(_ != ':')) + + When("the Organisation is deleted after it was granted access") + grantToOrganisation(recordId, organisationId, canUpdate = false).code should equal(200) + code_organisation.deleteOrganisation(organisationId) + Then("its grant is gone from the access list") + val accessList = makeGetRequest((dynamicEntity_Request / "test_rl" / recordId / "access").GET <@ (user1)) + (accessList.body \ "organisation_access").asInstanceOf[JArray].arr should be(empty) + } finally { + deleteSystemEntity(dynamicEntityId) + code_organisation.deleteOrganisation(organisationId) + } + } + } + + private val code_organisation = code.organisation.Organisations } diff --git a/obp-api/src/test/scala/code/api/v7_0_0/DeleteEntitlementAtOneBankTest.scala b/obp-api/src/test/scala/code/api/v7_0_0/DeleteEntitlementAtOneBankTest.scala new file mode 100644 index 0000000000..6f6974ae5a --- /dev/null +++ b/obp-api/src/test/scala/code/api/v7_0_0/DeleteEntitlementAtOneBankTest.scala @@ -0,0 +1,86 @@ +/** +Open Bank Project - API +Copyright (C) 2011-2026, TESOBE GmbH. + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +Email: contact@tesobe.com +TESOBE GmbH. +Osloer Strasse 16/17 +Berlin 13359, Germany + +This product includes software developed at +TESOBE (http://www.tesobe.com/) + + */ + +package code.api.v7_0_0 + +import code.api.util.APIUtil.OAuth._ +import code.api.util.ApiRole._ +import code.api.util.ErrorMessages._ +import code.api.v7_0_0.Http4s700.Implementations7_0_0 +import code.entitlement.Entitlement +import code.setup.ServerSetupWithTestData +import com.github.dwickern.macros.NameOf.nameOf +import com.openbankproject.commons.model.ErrorMessage +import com.openbankproject.commons.util.ApiVersion +import org.scalatest.Tag + +/** DELETE /banks/BANK_ID/entitlements/ENTITLEMENT_ID: CanDeleteEntitlementAtOneBank at that bank is enough. */ +class DeleteEntitlementAtOneBankTest extends ServerSetupWithTestData { + + object VersionOfApi extends Tag(ApiVersion.v7_0_0.toString) + object ApiEndpoint extends Tag(nameOf(Implementations7_0_0.deleteEntitlementAtOneBank)) + + def v7 = baseRequest / "obp" / "v7.0.0" + + def errorOf(response: code.setup.APIResponse): String = response.body.extract[ErrorMessage].message + + /** A Role held by user2 at the bank, for user1 to delete. */ + def grantToUser2(bankId: String): String = + Entitlement.entitlement.vend.addEntitlement(bankId, resourceUser2.userId, CanGetCustomersAtOneBank.toString) + .map(_.entitlementId).openOrThrowException("could not create the Entitlement") + + feature("Delete an Entitlement at one bank") { + scenario("Anonymous is 401; without the Role it is 403", ApiEndpoint, VersionOfApi) { + val entitlementId = grantToUser2(testBankId1.value) + val path = v7 / "banks" / testBankId1.value / "entitlements" / entitlementId + makeDeleteRequest(path.DELETE).code should equal(401) + val noRole = makeDeleteRequest(path.DELETE <@ (user1)) + noRole.code should equal(403) + errorOf(noRole) should startWith(UserHasMissingRoles) + Entitlement.entitlement.vend.getEntitlementById(entitlementId).isDefined should equal(true) + } + + scenario("The Role at the bank deletes an Entitlement there, and only there", ApiEndpoint, VersionOfApi) { + Entitlement.entitlement.vend.addEntitlement(testBankId1.value, resourceUser1.userId, CanDeleteEntitlementAtOneBank.toString) + + val atThisBank = grantToUser2(testBankId1.value) + makeDeleteRequest((v7 / "banks" / testBankId1.value / "entitlements" / atThisBank).DELETE <@ (user1)).code should equal(204) + Entitlement.entitlement.vend.getEntitlementById(atThisBank).isDefined should equal(false) + + Then("an Entitlement at another bank is not found through this bank") + val atOtherBank = grantToUser2(testBankId2.value) + val wrongBank = makeDeleteRequest((v7 / "banks" / testBankId1.value / "entitlements" / atOtherBank).DELETE <@ (user1)) + wrongBank.code should equal(404) + errorOf(wrongBank) should startWith(EntitlementNotFound) + Entitlement.entitlement.vend.getEntitlementById(atOtherBank).isDefined should equal(true) + + And("the Role at one bank does not reach the other bank") + makeDeleteRequest((v7 / "banks" / testBankId2.value / "entitlements" / atOtherBank).DELETE <@ (user1)).code should equal(403) + Entitlement.entitlement.vend.getEntitlementById(atOtherBank).isDefined should equal(true) + } + } +} diff --git a/obp-api/src/test/scala/code/api/v7_0_0/MyAccountsByRoutingRegexTest.scala b/obp-api/src/test/scala/code/api/v7_0_0/MyAccountsByRoutingRegexTest.scala new file mode 100644 index 0000000000..5182afeb4f --- /dev/null +++ b/obp-api/src/test/scala/code/api/v7_0_0/MyAccountsByRoutingRegexTest.scala @@ -0,0 +1,119 @@ +/** +Open Bank Project - API +Copyright (C) 2011-2026, TESOBE GmbH. + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +Email: contact@tesobe.com +TESOBE GmbH. +Osloer Strasse 16/17 +Berlin 13359, Germany + +This product includes software developed at +TESOBE (http://www.tesobe.com/) + + */ +package code.api.v7_0_0 + +import code.api.util.APIUtil +import code.api.util.APIUtil.OAuth._ +import code.api.util.ErrorMessages.{AuthenticatedUserIsRequired, InvalidAccountRoutingAddressRegex} +import code.api.v4_0_0.ModeratedAccountsJSON400 +import code.api.v6_0_0.V600ServerSetup +import code.model.dataAccess.BankAccountRouting +import com.github.dwickern.macros.NameOf.nameOf +import com.openbankproject.commons.model.ErrorMessage +import com.openbankproject.commons.util.ApiVersion +import org.scalatest.Tag + +/** POST /my/accounts/account-routing-regex-query, and the v4.0.0 endpoint it replaces not being served at v7.0.0. */ +class MyAccountsByRoutingRegexTest extends V600ServerSetup { + + def v7 = baseRequest / "obp" / "v7.0.0" + object VersionOfApi extends Tag(ApiVersion.v7_0_0.toString) + object ApiEndpoint1 extends Tag(nameOf(Http4s700MyAccounts.getMyAccountsByAccountRoutingRegex)) + + private val query = v7 / "my" / "accounts" / "account-routing-regex-query" + private def body(address: String) = + s"""{"bank_id": null, "account_routing": {"scheme": "AccountNumber", "address": "$address"}}""" + private def message(r: code.setup.APIResponse) = r.body.extract[ErrorMessage].message + + /** A routing address on a test account user1 holds the owner view of, unique to this test run. */ + private def routedAccount(): String = { + val prefix = "MYREGEX" + APIUtil.generateUUID().replace("-", "").take(12).toUpperCase + BankAccountRouting.create + .BankId(testBankId1.value) + .AccountId(testAccountId0.value) + .AccountRoutingScheme("AccountNumber") + .AccountRoutingAddress(prefix + "-EUR") + .saveMe() + prefix + } + + feature(s"test ${ApiEndpoint1.name} - Unauthorized access") { + scenario("Without a login the caller gets 401", ApiEndpoint1, VersionOfApi) { + val response = makePostRequest(query.POST, body("123456789-[A-Z]{3}")) + response.code should equal(401) + message(response) should equal(AuthenticatedUserIsRequired) + } + } + + feature(s"test ${ApiEndpoint1.name} - Authorized access") { + scenario("The owner finds their account; another user finds nothing", ApiEndpoint1, VersionOfApi) { + val prefix = routedAccount() + + When("user1, who holds the owner view of the account, searches") + val mine = makePostRequest(query.POST <@ user1, body("^" + prefix)) + Then("the account is returned") + mine.code should equal(200) + mine.body.extract[ModeratedAccountsJSON400].accounts.map(_.id) should equal(List(testAccountId0.value)) + + When("user2, who has no view of it, searches with the same pattern") + val theirs = makePostRequest(query.POST <@ user2, body("^" + prefix)) + Then("nothing is returned, and nothing about user1's account") + theirs.code should equal(200) + theirs.body.extract[ModeratedAccountsJSON400].accounts should be(List.empty) + theirs.body.toString.contains(testAccountId0.value) should be(false) + + When("user1 searches with a pattern that matches none of their accounts") + val none = makePostRequest(query.POST <@ user1, body("^" + prefix + "-[A-Z]{4}$")) + Then("the list is empty") + none.code should equal(200) + none.body.extract[ModeratedAccountsJSON400].accounts should be(List.empty) + } + + scenario("A pattern that is not a valid regular expression gets 400", ApiEndpoint1, VersionOfApi) { + val response = makePostRequest(query.POST <@ user1, body("123456789-[A-Z")) + response.code should equal(400) + message(response) should include(InvalidAccountRoutingAddressRegex) + } + } + + feature("The v4.0.0 endpoint it replaces") { + scenario("is not served at v7.0.0, and is still served at v4.0.0", ApiEndpoint1, VersionOfApi) { + val oldPath = List("management", "accounts", "account-routing-regex-query") + val atV7 = makePostRequest(oldPath.foldLeft(v7)(_ / _).POST <@ user1, body("^MYREGEX")) + atV7.code should equal(404) + val v4 = baseRequest / "obp" / "v4.0.0" + val atV4 = makePostRequest(oldPath.foldLeft(v4)(_ / _).POST <@ user1, body("^MYREGEX")) + atV4.code should equal(200) + } + + scenario("is not listed in the v7.0.0 resource docs", ApiEndpoint1, VersionOfApi) { + val names = Http4s700.allResourceDocs.map(_.partialFunctionName) + names should contain(nameOf(Http4s700MyAccounts.getMyAccountsByAccountRoutingRegex)) + names should not contain "getAccountsByAccountRoutingRegex" + } + } +} diff --git a/obp-api/src/test/scala/code/api/v7_0_0/OrganisationTest.scala b/obp-api/src/test/scala/code/api/v7_0_0/OrganisationTest.scala new file mode 100644 index 0000000000..8af33245f9 --- /dev/null +++ b/obp-api/src/test/scala/code/api/v7_0_0/OrganisationTest.scala @@ -0,0 +1,321 @@ +/** +Open Bank Project - API +Copyright (C) 2011-2026, TESOBE GmbH. + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see . + +Email: contact@tesobe.com +TESOBE GmbH. +Osloer Strasse 16/17 +Berlin 13359, Germany + +This product includes software developed at +TESOBE (http://www.tesobe.com/) + + */ + +package code.api.v7_0_0 + +import code.api.util.APIUtil.OAuth._ +import code.api.util.ApiRole._ +import code.api.util.ErrorMessages._ +import code.consumer.Consumers +import code.entitlement.Entitlement +import code.setup.ServerSetupWithTestData +import com.github.dwickern.macros.NameOf.nameOf +import com.openbankproject.commons.model.ErrorMessage +import com.openbankproject.commons.util.ApiVersion +import org.json4s._ +import org.json4s.native.Serialization.write +import org.scalatest.Tag + +import java.util.UUID + +/** + * Organisations, and the /my/consumers endpoints with which a Consumer's owners read it + * (todo/todo_organisations.md, todo/todo_consumer_owner_access.md). + * + * user1 creates the Organisation and adds user2 as a member; user3 is an outsider. + */ +class OrganisationTest extends ServerSetupWithTestData { + + object VersionOfApi extends Tag(ApiVersion.v7_0_0.toString) + object CreateMyOrganisation extends Tag(nameOf(Http4s700Organisations.createMyOrganisation)) + object GetMyOrganisations extends Tag(nameOf(Http4s700Organisations.getMyOrganisations)) + object GetMyOrganisation extends Tag(nameOf(Http4s700Organisations.getMyOrganisation)) + object UpdateMyOrganisation extends Tag(nameOf(Http4s700Organisations.updateMyOrganisation)) + object DeleteMyOrganisation extends Tag(nameOf(Http4s700Organisations.deleteMyOrganisation)) + object GetMyOrganisationMembers extends Tag(nameOf(Http4s700Organisations.getMyOrganisationMembers)) + object AddMyOrganisationMember extends Tag(nameOf(Http4s700Organisations.addMyOrganisationMember)) + object UpdateMyOrganisationMember extends Tag(nameOf(Http4s700Organisations.updateMyOrganisationMember)) + object RemoveMyOrganisationMember extends Tag(nameOf(Http4s700Organisations.removeMyOrganisationMember)) + object CreateOrganisation extends Tag(nameOf(Http4s700Organisations.createOrganisation)) + object GetOrganisations extends Tag(nameOf(Http4s700Organisations.getOrganisations)) + object GetOrganisationMembers extends Tag(nameOf(Http4s700Organisations.getOrganisationMembers)) + object UpdateOrganisationStatus extends Tag(nameOf(Http4s700Organisations.updateOrganisationStatus)) + object GetMyConsumers extends Tag(nameOf(Http4s700Organisations.getMyConsumers)) + object GetMyConsumer extends Tag(nameOf(Http4s700Organisations.getMyConsumer)) + object GetMyConsumerUsage extends Tag(nameOf(Http4s700Organisations.getMyConsumerUsage)) + object GetMyConsumerScopes extends Tag(nameOf(Http4s700Organisations.getMyConsumerScopes)) + object GetMyConsumerApiProductSubscriptions extends Tag(nameOf(Http4s700Organisations.getMyConsumerApiProductSubscriptions)) + object UpdateMyConsumerOrganisation extends Tag(nameOf(Http4s700Organisations.updateMyConsumerOrganisation)) + + def v7 = baseRequest / "obp" / "v7.0.0" + + def errorOf(response: code.setup.APIResponse): String = response.body.extract[ErrorMessage].message + + def createOwnedConsumer(ownerUserId: String, label: String, enabled: Boolean = true): String = Consumers.consumers.vend.createConsumer( + key = Some(UUID.randomUUID().toString.replace("-", "")), + secret = Some(UUID.randomUUID().toString.replace("-", "")), + isActive = Some(enabled), + name = Some(s"organisation-test-$label-" + UUID.randomUUID().toString.take(8)), + appType = None, + description = Some("created by OrganisationTest"), + developerEmail = Some(s"$label@example.com"), + redirectURL = None, + createdByUserId = Some(ownerUserId), + None, None, None + ).map(_.consumerId.get).openOrThrowException("could not create test consumer") + + def createOrganisation(name: String, as: Option[(Consumer, Token)]): MyOrganisationJsonV700 = { + val response = makePostRequest((v7 / "my" / "organisations").POST <@ (as), + write(PostOrganisationJsonV700(name, Some("A test organisation"), None))) + response.code should equal(201) + response.body.extract[MyOrganisationJsonV700] + } + + def addMember(organisationId: String, userId: String, memberRole: String, as: Option[(Consumer, Token)]) = + makePostRequest((v7 / "my" / "organisations" / organisationId / "members").POST <@ (as), + write(PostOrganisationMemberJsonV700(userId, memberRole))) + + def moveConsumer(consumerId: String, organisationId: Option[String], as: Option[(Consumer, Token)]) = + makePutRequest((v7 / "my" / "consumers" / consumerId / "organisation").PUT <@ (as), + write(PutConsumerOrganisationJsonV700(organisationId))) + + def myConsumerIds(as: Option[(Consumer, Token)]): List[String] = { + val response = makeGetRequest((v7 / "my" / "consumers").GET <@ (as)) + response.code should equal(200) + response.body.extract[MyConsumersJsonV700].consumers.map(_.consumer_id) + } + + feature("Organisations and their members") { + scenario("Anyone logged in creates an Organisation and is its admin; outsiders get 404; anonymous 401", + CreateMyOrganisation, GetMyOrganisations, GetMyOrganisation, VersionOfApi) { + makePostRequest((v7 / "my" / "organisations").POST, write(PostOrganisationJsonV700("x", None, None))).code should equal(401) + val blank = makePostRequest((v7 / "my" / "organisations").POST <@ (user1), write(PostOrganisationJsonV700(" ", None, None))) + blank.code should equal(400) + errorOf(blank) should startWith(InvalidOrganisationName) + Then("an Organisation you create for yourself cannot be put at a bank") + val atBank = makePostRequest((v7 / "my" / "organisations").POST <@ (user1), + s"""{"bank_id":"${testBankId1.value}","name":"Fintech at a bank"}""") + atBank.code should equal(400) + errorOf(atBank) should startWith(MyOrganisationBankIdNotAllowed) + And("sending SYS is accepted, since that is where it goes anyway") + val atSys = makePostRequest((v7 / "my" / "organisations").POST <@ (user1), """{"bank_id":"SYS","name":"Fintech at SYS"}""") + atSys.code should equal(201) + atSys.body.extract[MyOrganisationJsonV700].bank_id should equal("SYS") + + val organisation = createOrganisation("Fintech A", user1) + organisation.member_role should equal("admin") + organisation.bank_id should equal("SYS") + organisation.status should equal("active") + organisation.created_by_user_id should equal(resourceUser1.userId) + + val mine = makeGetRequest((v7 / "my" / "organisations").GET <@ (user1)) + mine.body.extract[MyOrganisationsJsonV700].organisations.map(_.organisation_id) should contain(organisation.organisation_id) + makeGetRequest((v7 / "my" / "organisations" / organisation.organisation_id).GET <@ (user1)).code should equal(200) + val outsider = makeGetRequest((v7 / "my" / "organisations" / organisation.organisation_id).GET <@ (user3)) + outsider.code should equal(404) + errorOf(outsider) should startWith(OrganisationNotFound) + } + + scenario("Admins manage members; members cannot; the last admin stays", + AddMyOrganisationMember, UpdateMyOrganisationMember, RemoveMyOrganisationMember, GetMyOrganisationMembers, UpdateMyOrganisation, VersionOfApi) { + val organisation = createOrganisation("Fintech B", user1) + val organisationId = organisation.organisation_id + + addMember(organisationId, resourceUser2.userId, "owner", user1).code should equal(400) + addMember(organisationId, "no-such-user-" + UUID.randomUUID(), "member", user1).code should equal(404) + addMember(organisationId, resourceUser2.userId, "member", user1).code should equal(201) + val again = addMember(organisationId, resourceUser2.userId, "member", user1) + again.code should equal(409) + errorOf(again) should startWith(OrganisationMemberAlreadyExists) + + val members = makeGetRequest((v7 / "my" / "organisations" / organisationId / "members").GET <@ (user2)) + members.code should equal(200) + members.body.extract[OrganisationMembersJsonV700].members.map(_.user_id) should contain theSameElementsAs + List(resourceUser1.userId, resourceUser2.userId) + + val memberAdds = addMember(organisationId, resourceUser3.userId, "member", user2) + memberAdds.code should equal(403) + errorOf(memberAdds) should startWith(OrganisationAdminRequired) + makePutRequest((v7 / "my" / "organisations" / organisationId).PUT <@ (user2), + write(PutOrganisationJsonV700(Some("Renamed"), None, None))).code should equal(403) + val renamed = makePutRequest((v7 / "my" / "organisations" / organisationId).PUT <@ (user1), + write(PutOrganisationJsonV700(Some("Fintech B Ltd"), None, None))) + renamed.code should equal(200) + renamed.body.extract[MyOrganisationJsonV700].name should equal("Fintech B Ltd") + + val demoteLastAdmin = makePutRequest((v7 / "my" / "organisations" / organisationId / "members" / resourceUser1.userId).PUT <@ (user1), + write(PutOrganisationMemberJsonV700("member"))) + demoteLastAdmin.code should equal(400) + errorOf(demoteLastAdmin) should startWith(OrganisationNeedsAnAdmin) + makeDeleteRequest((v7 / "my" / "organisations" / organisationId / "members" / resourceUser1.userId).DELETE <@ (user1)).code should equal(400) + + makePutRequest((v7 / "my" / "organisations" / organisationId / "members" / resourceUser2.userId).PUT <@ (user1), + write(PutOrganisationMemberJsonV700("admin"))).code should equal(200) + Then("with a second admin, the first may leave") + makeDeleteRequest((v7 / "my" / "organisations" / organisationId / "members" / resourceUser1.userId).DELETE <@ (user1)).code should equal(204) + makeGetRequest((v7 / "my" / "organisations" / organisationId).GET <@ (user1)).code should equal(404) + } + } + + feature("Consumers of an Organisation, and /my/consumers") { + scenario("A personal Consumer is its creator's; in an Organisation it is the members'", + GetMyConsumers, GetMyConsumer, UpdateMyConsumerOrganisation, DeleteMyOrganisation, VersionOfApi) { + val consumerId = createOwnedConsumer(resourceUser1.userId, "user1") + myConsumerIds(user1) should contain(consumerId) + myConsumerIds(user2) should not contain consumerId + makeGetRequest((v7 / "my" / "consumers" / consumerId).GET <@ (user2)).code should equal(404) + + val organisation = createOrganisation("Fintech C", user1) + val organisationId = organisation.organisation_id + addMember(organisationId, resourceUser2.userId, "member", user1).code should equal(201) + + When("user2, a member but not an admin, tries to move user1's Consumer in") + moveConsumer(consumerId, Some(organisationId), user2).code should equal(404) + When("user1, the creator and an admin, moves it in") + val moved = moveConsumer(consumerId, Some(organisationId), user1) + moved.code should equal(200) + moved.body.extract[MyConsumerJsonV700].organisation_id should equal(Some(organisationId)) + + Then("members see it, outsiders do not") + myConsumerIds(user2) should contain(consumerId) + makeGetRequest((v7 / "my" / "consumers" / consumerId).GET <@ (user2)).code should equal(200) + myConsumerIds(user3) should not contain consumerId + + And("a member may not move it out; an admin may") + val memberMoves = moveConsumer(consumerId, None, user2) + memberMoves.code should equal(403) + errorOf(memberMoves) should startWith(OrganisationAdminRequired) + + And("the Organisation cannot be deleted while it has Consumers") + val deleteWithConsumers = makeDeleteRequest((v7 / "my" / "organisations" / organisationId).DELETE <@ (user1)) + deleteWithConsumers.code should equal(409) + errorOf(deleteWithConsumers) should startWith(OrganisationHasConsumers) + + moveConsumer(consumerId, None, user1).code should equal(200) + myConsumerIds(user2) should not contain consumerId + makeDeleteRequest((v7 / "my" / "organisations" / organisationId).DELETE <@ (user2)).code should equal(403) + makeDeleteRequest((v7 / "my" / "organisations" / organisationId).DELETE <@ (user1)).code should equal(204) + } + + scenario("The creator no longer acts alone once the Consumer belongs to an Organisation they left", + GetMyConsumer, VersionOfApi) { + val consumerId = createOwnedConsumer(resourceUser1.userId, "leaver") + val organisation = createOrganisation("Fintech D", user1) + addMember(organisation.organisation_id, resourceUser2.userId, "admin", user1).code should equal(201) + moveConsumer(consumerId, Some(organisation.organisation_id), user1).code should equal(200) + makeDeleteRequest((v7 / "my" / "organisations" / organisation.organisation_id / "members" / resourceUser1.userId).DELETE <@ (user1)).code should equal(204) + makeGetRequest((v7 / "my" / "consumers" / consumerId).GET <@ (user1)).code should equal(404) + makeGetRequest((v7 / "my" / "consumers" / consumerId).GET <@ (user2)).code should equal(200) + } + + scenario("A disabled Consumer is shown with enabled false; usage, Scopes and subscriptions are readable; no secret", + GetMyConsumer, GetMyConsumerUsage, GetMyConsumerScopes, GetMyConsumerApiProductSubscriptions, VersionOfApi) { + val consumerId = createOwnedConsumer(resourceUser1.userId, "disabled", enabled = false) + val consumer = makeGetRequest((v7 / "my" / "consumers" / consumerId).GET <@ (user1)) + consumer.code should equal(200) + consumer.body.extract[MyConsumerJsonV700].enabled should equal(false) + (consumer.body \ "consumer_key") should equal(JNothing) + (consumer.body \ "secret") should equal(JNothing) + + val usage = makeGetRequest((v7 / "my" / "consumers" / consumerId / "usage").GET <@ (user1)) + usage.code should equal(200) + (usage.body \ "consumer_id").extract[String] should equal(consumerId) + (usage.body \ "active_rate_limits") should not equal JNothing + (usage.body \ "call_counters") should not equal JNothing + + val scopes = makeGetRequest((v7 / "my" / "consumers" / consumerId / "scopes").GET <@ (user1)) + scopes.code should equal(200) + scopes.body.extract[MyConsumerScopesJsonV700].scopes should equal(Nil) + + val subscriptions = makeGetRequest((v7 / "my" / "consumers" / consumerId / "api-product-subscriptions").GET <@ (user1)) + subscriptions.code should equal(200) + + List("usage", "scopes", "api-product-subscriptions").foreach { part => + makeGetRequest((v7 / "my" / "consumers" / consumerId / part).GET <@ (user3)).code should equal(404) + } + makeGetRequest((v7 / "my" / "consumers" / consumerId / "usage").GET).code should equal(401) + } + } + + feature("Staff") { + scenario("Staff Roles are held at the Organisation's bank_id; a suspended Organisation's members cannot act for its Consumers", + GetOrganisations, UpdateOrganisationStatus, VersionOfApi) { + val organisation = createOrganisation("Fintech E", user1) + val consumerId = createOwnedConsumer(resourceUser1.userId, "suspended") + moveConsumer(consumerId, Some(organisation.organisation_id), user1).code should equal(200) + + makeGetRequest((v7 / "management" / "organisations").GET <@ (user3)).code should equal(403) + Entitlement.entitlement.vend.addEntitlement(testBankId1.value, resourceUser3.userId, CanGetOrganisationAtOneBank.toString) + Then("the Role at another bank_id does not show an Organisation at SYS") + makeGetRequest((v7 / "management" / "organisations" / organisation.organisation_id).GET <@ (user3)).code should equal(403) + Entitlement.entitlement.vend.addEntitlement("SYS", resourceUser3.userId, CanGetOrganisationAtOneBank.toString) + val all = makeGetRequest((v7 / "management" / "organisations").GET <@ (user3)) + all.code should equal(200) + all.body.extract[OrganisationsJsonV700].organisations.map(_.organisation_id) should contain(organisation.organisation_id) + + val statusPath = v7 / "management" / "organisations" / organisation.organisation_id / "status" + makePutRequest(statusPath.PUT <@ (user3), write(PutOrganisationStatusJsonV700("suspended"))).code should equal(403) + Entitlement.entitlement.vend.addEntitlement("SYS", resourceUser3.userId, CanUpdateOrganisationStatusAtOneBank.toString) + makePutRequest(statusPath.PUT <@ (user3), write(PutOrganisationStatusJsonV700("closed"))).code should equal(400) + makePutRequest(statusPath.PUT <@ (user3), write(PutOrganisationStatusJsonV700("suspended"))).code should equal(200) + + Then("the member still sees the Organisation but not its Consumer") + makeGetRequest((v7 / "my" / "organisations" / organisation.organisation_id).GET <@ (user1)).code should equal(200) + makeGetRequest((v7 / "my" / "consumers" / consumerId).GET <@ (user1)).code should equal(404) + + makePutRequest(statusPath.PUT <@ (user3), write(PutOrganisationStatusJsonV700("active"))).code should equal(200) + makeGetRequest((v7 / "my" / "consumers" / consumerId).GET <@ (user1)).code should equal(200) + } + + scenario("Staff create an Organisation with a first admin, and read its members", CreateOrganisation, GetOrganisationMembers, VersionOfApi) { + val body = write(PostManagementOrganisationJsonV700(Some(testBankId2.value), "Participant Bank", None, None, resourceUser2.userId)) + makePostRequest((v7 / "management" / "organisations").POST <@ (user1), body).code should equal(403) + Entitlement.entitlement.vend.addEntitlement(testBankId2.value, resourceUser1.userId, CanCreateOrganisationAtOneBank.toString) + val created = makePostRequest((v7 / "management" / "organisations").POST <@ (user1), body) + created.code should equal(201) + val organisation = created.body.extract[OrganisationJsonV700] + organisation.bank_id should equal(testBankId2.value) + + Then("the named first admin, not the member of staff, is its admin") + makeGetRequest((v7 / "my" / "organisations" / organisation.organisation_id).GET <@ (user2)).body + .extract[MyOrganisationJsonV700].member_role should equal("admin") + makeGetRequest((v7 / "my" / "organisations" / organisation.organisation_id).GET <@ (user1)).code should equal(404) + + val membersPath = v7 / "management" / "organisations" / organisation.organisation_id / "members" + makeGetRequest(membersPath.GET <@ (user1)).code should equal(403) + Entitlement.entitlement.vend.addEntitlement(testBankId2.value, resourceUser1.userId, CanGetOrganisationAtOneBank.toString) + val members = makeGetRequest(membersPath.GET <@ (user1)) + members.code should equal(200) + members.body.extract[OrganisationMembersJsonV700].members.map(_.user_id) should equal(List(resourceUser2.userId)) + + val listed = makeGetRequest((v7 / "management" / "organisations").GET < testBankId2.value) <@ (user1)) + listed.code should equal(200) + listed.body.extract[OrganisationsJsonV700].organisations.map(_.organisation_id) should equal(List(organisation.organisation_id)) + makeGetRequest((v7 / "management" / "organisations").GET < "SYS") <@ (user1)).code should equal(403) + } + } +} diff --git a/scripts/resource_doc_baseline/parity_allowlist.json b/scripts/resource_doc_baseline/parity_allowlist.json index 3f992f1b27..6d702393cb 100644 --- a/scripts/resource_doc_baseline/parity_allowlist.json +++ b/scripts/resource_doc_baseline/parity_allowlist.json @@ -1367,41 +1367,41 @@ "version": "v6_0_0", "endpoint": "createBankLevelDynamicEntity", "field": "description", - "reason": "Digest refresh: row-level access grant endpoint corrected from GET/POST to GET/PUT (matches Method.PUT route in Http4sDynamicEntity.scala), on top of the field-level access control and indexed/index docs already reviewed. Digest refresh 2026-10-02: documents the hide_field_from_public_access field flag. Digest refresh 2026-10-29: auth_mode UserOrApplication renamed to UserXORApplication (Scopes for the application acting as itself, Entitlements for a person); the former name is still accepted. Digest refresh 2026-10-29: auth_mode UserOrApplication renamed to UserXORApplication (Scopes for the application acting as itself, Entitlements for a person); the former name is still accepted. Digest refresh 2026-10-29: auth_mode UserOrApplication renamed to UserXORApplication (Scopes for the application acting as itself, Entitlements for a person); the former name is still accepted. Digest refresh 2026-10-29: auth_mode UserOrApplication renamed to UserXORApplication (Scopes for the application acting as itself, Entitlements for a person); the former name is still accepted. Digest refresh 2026-10-29: auth_mode UserOrApplication renamed to UserXORApplication (Scopes for the application acting as itself, Entitlements for a person); the former name is still accepted. Digest refresh 2026-11-10: auth_mode is removed (endpoint auth modes are gone); the text now says that the entity's Roles decide who may use its data endpoints.", + "reason": "Digest refresh: row-level access grant endpoint corrected from GET/POST to GET/PUT (matches Method.PUT route in Http4sDynamicEntity.scala), on top of the field-level access control and indexed/index docs already reviewed. Digest refresh 2026-10-02: documents the hide_field_from_public_access field flag. Digest refresh 2026-10-29: auth_mode UserOrApplication renamed to UserXORApplication (Scopes for the application acting as itself, Entitlements for a person); the former name is still accepted. Digest refresh 2026-10-29: auth_mode UserOrApplication renamed to UserXORApplication (Scopes for the application acting as itself, Entitlements for a person); the former name is still accepted. Digest refresh 2026-10-29: auth_mode UserOrApplication renamed to UserXORApplication (Scopes for the application acting as itself, Entitlements for a person); the former name is still accepted. Digest refresh 2026-10-29: auth_mode UserOrApplication renamed to UserXORApplication (Scopes for the application acting as itself, Entitlements for a person); the former name is still accepted. Digest refresh 2026-10-29: auth_mode UserOrApplication renamed to UserXORApplication (Scopes for the application acting as itself, Entitlements for a person); the former name is still accepted. Digest refresh 2026-11-10: auth_mode is removed (endpoint auth modes are gone); the text now says that the entity's Roles decide who may use its data endpoints. Digest refresh 2026-11-17: the row-level access paragraph now says an access entry can name an organisation_id as well as a user_id, and that use_row_level_access can be combined with has_community_access (not with has_public_access).", "lift_digest": "2e7c649041362776f7eec66ccbb9f025f3edfead992108d0fd5864af76e93961", - "http4s_digest": "b77a6503d0ca6497361d121f49b8eae398409cfe1ad49b59ce6cdc092fe1dcfd" + "http4s_digest": "c14aa9b9535499b763e2eb902edb1774b65cf105352e59e5df71c0c9bf34a149" }, { "version": "v6_0_0", "endpoint": "createSystemDynamicEntity", "field": "description", - "reason": "Digest refresh: row-level access grant endpoint corrected from GET/POST to GET/PUT (matches Method.PUT route in Http4sDynamicEntity.scala), on top of the field-level access control and indexed/index docs already reviewed. Digest refresh 2026-10-02: documents the hide_field_from_public_access field flag. Digest refresh 2026-11-10: auth_mode is removed (endpoint auth modes are gone); the text now says that the entity's Roles decide who may use its data endpoints.", + "reason": "Digest refresh: row-level access grant endpoint corrected from GET/POST to GET/PUT (matches Method.PUT route in Http4sDynamicEntity.scala), on top of the field-level access control and indexed/index docs already reviewed. Digest refresh 2026-10-02: documents the hide_field_from_public_access field flag. Digest refresh 2026-11-10: auth_mode is removed (endpoint auth modes are gone); the text now says that the entity's Roles decide who may use its data endpoints. Digest refresh 2026-11-17: the row-level access paragraph now says an access entry can name an organisation_id as well as a user_id, and that use_row_level_access can be combined with has_community_access (not with has_public_access).", "lift_digest": "81310cdd2be1c2b33d465cabd1604cedee38bfa1ecccae4b016d0f99aa443ab6", - "http4s_digest": "138cb03ffecb8f5ba4e90ed66a2873e23863d31a86bdcddc353621380746561d" + "http4s_digest": "3ac0f64ec4e482e4890abc20926259c6dfe57dfd649be1e5880a38a76e941099" }, { "version": "v6_0_0", "endpoint": "updateBankLevelDynamicEntity", "field": "description", - "reason": "Digest refresh: row-level access grant endpoint corrected from GET/POST to GET/PUT (matches Method.PUT route in Http4sDynamicEntity.scala), on top of the field-level access control and indexed/index docs already reviewed. Digest refresh 2026-10-02: documents the hide_field_from_public_access field flag. Digest refresh 2026-11-10: auth_mode is removed (endpoint auth modes are gone); the text now says that the entity's Roles decide who may use its data endpoints.", + "reason": "Digest refresh: row-level access grant endpoint corrected from GET/POST to GET/PUT (matches Method.PUT route in Http4sDynamicEntity.scala), on top of the field-level access control and indexed/index docs already reviewed. Digest refresh 2026-10-02: documents the hide_field_from_public_access field flag. Digest refresh 2026-11-10: auth_mode is removed (endpoint auth modes are gone); the text now says that the entity's Roles decide who may use its data endpoints. Digest refresh 2026-11-17: the row-level access paragraph now says an access entry can name an organisation_id as well as a user_id, and that use_row_level_access can be combined with has_community_access (not with has_public_access).", "lift_digest": "2d18665f9db52506a1b043ad7575b16ac52cedf0d11f036afd4a96b353eb8ddd", - "http4s_digest": "f0fc539d1a6058fe378ce8fd001f7f5f60ffb6c28dbf0ef44f02d22f7db55cea" + "http4s_digest": "c4f9df3991dc36e7215f3f749a654eed6d96eaf23d16e865fc269fdb0eba11a3" }, { "version": "v6_0_0", "endpoint": "updateMyDynamicEntity", "field": "description", - "reason": "Digest refresh: row-level access grant endpoint corrected from GET/POST to GET/PUT (matches Method.PUT route in Http4sDynamicEntity.scala), on top of the field-level access control and indexed/index docs already reviewed. Digest refresh 2026-10-02: documents the hide_field_from_public_access field flag. Digest refresh 2026-11-10: auth_mode is removed (endpoint auth modes are gone); the text now says that the entity's Roles decide who may use its data endpoints.", + "reason": "Digest refresh: row-level access grant endpoint corrected from GET/POST to GET/PUT (matches Method.PUT route in Http4sDynamicEntity.scala), on top of the field-level access control and indexed/index docs already reviewed. Digest refresh 2026-10-02: documents the hide_field_from_public_access field flag. Digest refresh 2026-11-10: auth_mode is removed (endpoint auth modes are gone); the text now says that the entity's Roles decide who may use its data endpoints. Digest refresh 2026-11-17: the row-level access paragraph now says an access entry can name an organisation_id as well as a user_id, and that use_row_level_access can be combined with has_community_access (not with has_public_access).", "lift_digest": "97f0c97cc592f89f4dba8a6641ad4b41f6ffa6f4f6e78bf3d3cc34a6a11f76e7", - "http4s_digest": "8f05614b7cb370ede150f2ef09c424303f23a1ba556c3531e60c74a161fcdfb2" + "http4s_digest": "1cf13771496c2d0673a405c3a150296b0a7e243dc6c502af56039d47d8a30237" }, { "version": "v6_0_0", "endpoint": "updateSystemDynamicEntity", "field": "description", - "reason": "Digest refresh: row-level access grant endpoint corrected from GET/POST to GET/PUT (matches Method.PUT route in Http4sDynamicEntity.scala), on top of the field-level access control and indexed/index docs already reviewed. Digest refresh 2026-10-02: documents the hide_field_from_public_access field flag. Digest refresh 2026-11-10: auth_mode is removed (endpoint auth modes are gone); the text now says that the entity's Roles decide who may use its data endpoints.", + "reason": "Digest refresh: row-level access grant endpoint corrected from GET/POST to GET/PUT (matches Method.PUT route in Http4sDynamicEntity.scala), on top of the field-level access control and indexed/index docs already reviewed. Digest refresh 2026-10-02: documents the hide_field_from_public_access field flag. Digest refresh 2026-11-10: auth_mode is removed (endpoint auth modes are gone); the text now says that the entity's Roles decide who may use its data endpoints. Digest refresh 2026-11-17: the row-level access paragraph now says an access entry can name an organisation_id as well as a user_id, and that use_row_level_access can be combined with has_community_access (not with has_public_access).", "lift_digest": "e28c2996f3fd54842534fd54d45d7ba49df8b346e65f541353be4fb5311b550c", - "http4s_digest": "ce26f4656c8c69376358260477e9ab0bb4051a1c043f83288a10519058b51f1c" + "http4s_digest": "0b69022e06f93f0e7e2ee843fedd886555828e90d4fc0bee6bb2a678b03015bc" }, { "version": "v3_0_0",