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 64e4adf49a..cb090e5ede 100644 --- a/obp-api/src/main/resources/docs/introductory_system_documentation.md +++ b/obp-api/src/main/resources/docs/introductory_system_documentation.md @@ -31,6 +31,8 @@ For more detailed information or the sources of truths, please refer to the indi - 3.13 [OBP-MCP (Model Context Protocol Server)](#313-obp-mcp-model-context-protocol-server) - 3.14 [OBP-Sentinel](#314-obp-sentinel) - 3.15 [OBP Bank Node](#315-obp-bank-node) + - 3.16 [OBP Cohort](#316-obp-cohort) + - 3.17 [Conformator](#317-conformator) 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) @@ -236,8 +238,10 @@ The Open Bank Project (OBP) is an open-source RESTful API platform for banks tha - **Keycloak Integration:** Production-grade OIDC provider support - **OBP Portal:** Developer portal where people sign up, register applications and try the API - **OBP-MCP:** Model Context Protocol server, so AI agents can find and call OBP endpoints -- **OBP-Sentinel:** Watches running OBP instances and suggests the improvements that matter most +- **OBP-Sentinel (OBP Senti):** Watches running OBP instances and suggests the improvements that matter most - **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 --- @@ -1399,6 +1403,8 @@ The server starts at `http://localhost:9100` with the MCP endpoint at `/mcp`. ### 3.14 OBP-Sentinel +OBP-Sentinel, or Senti for short, is sold as **OBP Senti**, and as **TESOBE Senti** for systems that do not use OBP. See https://senti.tesobe.com. + **Purpose:** Watches running OBP-API instances, and the apps around them (API Explorer II, API Manager, the Portal, OBP-OIDC), works out what is actually going wrong or getting slower, and suggests the few improvements that matter most. **How it works:** @@ -1421,6 +1427,33 @@ See the Glossary item OBP-Sentinel. See the Glossary items OBP Bank Node, Connector and Adapter. +### 3.16 OBP Cohort + +**Purpose:** Runs startup programmes for incubators, accelerators, banks, regulators and innovation hubs, from the call for applications to graduation, in English and Arabic. + +**Key Features:** + +- 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 +- 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. + +### 3.17 Conformator + +**Purpose:** Lets a regulator test the open banking APIs of the banks, payment service providers and third-party providers it supervises against the agreed standard, review the results and issue conformance reports. + +**Key Features:** + +- 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 +- 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. + --- ## 4. Standards Compliance @@ -2739,7 +2772,7 @@ GET /obp/v5.1.0/management/consumers **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 or a Bank Node. Only a Platform App can act as itself on its Consumer's Scopes (see 8.7). +**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). 1. An administrator marks the Consumer as a Platform App (Role CanCreatePlatformApp). 2. The app declares the Scopes it needs, and what each one is for, every time it starts. diff --git a/obp-api/src/main/scala/code/api/DirectLoginRoutes.scala b/obp-api/src/main/scala/code/api/DirectLoginRoutes.scala index b63552eff2..d69f1c5cda 100644 --- a/obp-api/src/main/scala/code/api/DirectLoginRoutes.scala +++ b/obp-api/src/main/scala/code/api/DirectLoginRoutes.scala @@ -98,7 +98,10 @@ object DirectLoginRoutes { triple <- DirectLogin.validatorFutureWithParams("authorizationToken", "POST", params) (httpCode, message, dlParams) = triple tokenTriple = DirectLogin.createTokenCommonPart(httpCode, message, dlParams) - _ <- Future(DirectLogin.grantEntitlementsToUseDynamicEndpointsInSpacesInDirectLogin(tokenTriple._3)) + // The post-login grant runs only when a token was issued. On a refused login the third value is a state code + // (0, locked, email not validated, rate limited), not a user id, so the grant would find no user and log an ERROR. + _ <- if (tokenTriple._1 == 200) Future(DirectLogin.grantEntitlementsToUseDynamicEndpointsInSpacesInDirectLogin(tokenTriple._3)) + else Future.unit } yield { if (tokenTriple._1 == 200) JSONFactory600.createTokenJSON(tokenTriple._2) else code.api.util.APIUtil.unboxFullOrFail(Empty, None, tokenTriple._2, tokenTriple._1) 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 3fe5a544b3..6934c6df0a 100644 --- a/obp-api/src/main/scala/code/api/util/Glossary.scala +++ b/obp-api/src/main/scala/code/api/util/Glossary.scala @@ -7334,9 +7334,11 @@ object Glossary extends MdcLoggable { s""" |# OBP-Sentinel | - |**OBP-Sentinel** watches running OBP-API instances, and the apps around them (API Explorer II, the API Manager, the Portal, OBP-OIDC), for hours. It works out what is actually going wrong or getting slower, and suggests the few improvements that matter most. Fewer, better suggestions is the point. + |**OBP-Sentinel**, or Senti for short, watches running OBP-API instances, and the apps around them (API Explorer II, the API Manager, the Portal, OBP-OIDC), for hours. It works out what is actually going wrong or getting slower, and suggests the few improvements that matter most. Fewer, better suggestions is the point. | - |Watching is plain code and costs nothing. Only the analyst, the source review and the questions a person asks on a finding (Trace history, Look again) use Claude, each with a spending limit. + |It is sold as OBP Senti, and as TESOBE Senti for systems that do not use OBP. See https://senti.tesobe.com. + | + |Watching is plain code and costs nothing. Only three things use Claude: the analyst, the source review, and the questions a person asks on a finding (Trace history, Look again). Each has a spending limit. | |## 1. Watching | @@ -7364,13 +7366,13 @@ object Glossary extends MdcLoggable { | |LEVEL is a log level (error, warning, info, debug, trace) or `all`. Each app lists these endpoints on its `/status` page. | - |They are guarded by the same Roles as OBP-API's own endpoints: CanGetSystemLogCacheError, CanGetSystemLogCacheWarning and so on, one per level (`all` needs CanGetSystemLogCacheAll) and CanGetTelemetry. The app does not decide this itself: it passes the caller's token to OBP-API (GET /obp/v7.0.0/banks/SYS/my/roles/ROLE) and answers only if OBP-API says the Role is held. A call with no token gets 401, and a call without the Role gets 403. + |They are guarded by the same Roles as OBP-API's own endpoints: CanGetSystemLogCacheError, CanGetSystemLogCacheWarning and so on, one per level (`all` needs CanGetSystemLogCacheAll) and CanGetTelemetry. The app does not decide this itself. It passes the caller's token to OBP-API (GET /obp/v7.0.0/banks/SYS/my/roles/ROLE), and answers only if OBP-API says the Role is held. A call with no token gets 401, and a call without the Role gets 403. | - |Sentinel finds the apps in OBP-API's app directory (GET /obp/v6.0.0/app-directory: public_obp_api_explorer_url, public_obp_api_manager_url, public_obp_portal_url, public_obp_oidc_url) and watches each like a small instance of its own, with its own findings, using its OBP-API instance's token. The analyst then reads the app's own source. An app has no aggregate metrics and no source review. + |Sentinel finds the apps in OBP-API's app directory (GET /obp/v6.0.0/app-directory: public_obp_api_explorer_url, public_obp_api_manager_url, public_obp_portal_url, public_obp_oidc_url). It watches each like a small instance of its own, with its own findings, using its OBP-API instance's token. The analyst then reads the app's own source. An app has no aggregate metrics and no source review. | |## 2. The analyst | - |Every few hours, once Sentinel has watched for long enough, Claude reads a summary of what was collected (the last hours compared with the hours before) and reads the source code to find the cause of what stands out. Each problem it is confident about becomes a **finding**, scored by: + |Once Sentinel has watched for long enough, Claude reads a summary every few hours. It compares the last hours with the hours before. It then reads the source code to find the cause of what stands out. Each problem it is confident about becomes a **finding**, scored by: | |- **Impact**: how much it hurts users or the service; |- **Confidence**: how sure the analyst is about the cause; @@ -7380,11 +7382,18 @@ object Glossary extends MdcLoggable { | |## 3. Source review | - |Besides following the logs, Sentinel can read the code of the endpoints each instance serves, looking for security problems such as SQL injection or missing authorisation checks. Go and Stop turn it on and off. It starts with the endpoints anyone can call without a login, then those that need a login, then those whose Role someone holds. It remembers what it read: an endpoint is read again only when its code changes. + |Sentinel can also read the code of the endpoints each instance serves. It looks for security problems such as SQL injection or missing authorisation checks. Go and Stop turn it on and off. It starts with the endpoints anyone can call without a login, then those that need a login, then those whose Role someone holds. It remembers what it read: an endpoint is read again only when its code changes. | |## 4. Suggestions | - |A finding is suggested only if Sentinel has watched for long enough (4 hours by default), its priority is high enough, it was seen in more than one 15-minute period, and it was not already suggested, acted on, dismissed or fixed. At most 3 suggestions are made at a time, and at most 10 a week. When nothing qualifies, Sentinel says so rather than inventing work. + |A finding is suggested only when all of these are true: + | + |- Sentinel has watched for long enough (4 hours by default). + |- Its priority is high enough. + |- It was seen in more than one 15-minute period. + |- It was not already suggested, acted on, dismissed or fixed. + | + |At most 3 suggestions are made at a time, and at most 10 a week. When nothing qualifies, Sentinel says so rather than inventing work. | |## Using the page | @@ -7393,7 +7402,7 @@ object Glossary extends MdcLoggable { |Each finding shows its evidence, why it happens, where in the code, and the suggested change. The copy button next to its title copies it all as text, ready to give to a coding agent. | |- **Trace history** lists the commits that changed the lines the finding names, and Claude says which commit introduced the problem (at most $$0.30). - |- **Look again: still an issue?** has Claude read the code the instance runs now, the commits since the finding was made, and whether its log messages are still seen. It answers in one line: still an issue, fixed (and by which commit), or could not tell. It takes a few minutes and costs at most $$0.50. While it works, the page shows how long it has been going and the command it is running. It does not change the finding's status. + |- **Look again: still an issue?** has Claude read the code the instance runs now and the commits since the finding was made. It also checks whether the finding's log messages are still seen. It answers in one line: still an issue, fixed (and by which commit), or could not tell. It takes a few minutes and costs at most $$0.50. While it works, the page shows how long it has been going and the command it is running. It does not change the finding's status. |- **Look again at the security findings to review**, above the list, does the same for each security finding in To review, one at a time. Those Claude finds fixed are marked fixed and move to Done, with Claude's answer as the comment. | |Then answer, with a comment for the analyst if you like: @@ -7408,7 +7417,11 @@ object Glossary extends MdcLoggable { | |## The Secured check | - |Once an hour Sentinel calls the endpoints it reads (log cache, Telemetry and, for OBP-API, aggregate metrics) without a token. They must refuse. The header shows **Secured** when every one refused (401 or 403), **Open** when at least one answered with data (fix this first: anyone can read those logs), and **Could not tell** when some gave no answer or an unexpected one, such as 404. + |Once an hour Sentinel calls the endpoints it reads (log cache, Telemetry and, for OBP-API, aggregate metrics) without a token. They must refuse. The header shows one of these: + | + |- **Secured:** every one refused (401 or 403). + |- **Open:** at least one answered with data. Fix this first, because anyone can read those logs. + |- **Could not tell:** some gave no answer, or an unexpected one such as 404. | |## What Sentinel needs | @@ -7423,6 +7436,52 @@ object Glossary extends MdcLoggable { |""".stripMargin) + glossaryItems += GlossaryItem( + title = "OBP Cohort", + description = + s""" + |# OBP Cohort + | + |**OBP Cohort** runs startup programmes for incubators, accelerators, banks, regulators and innovation hubs, from the call for applications to graduation, in English and Arabic. + | + |- **Call:** a call is published on a public site, and anyone can apply. + |- **Apply:** forms with attachments, saved drafts, and eligibility checked when the form is sent. + |- **Evaluate:** reviewers declare any conflict of interest, then score each application against the call's weighted rubric. Staff see a ranked shortlist and record each decision. + |- **Deliver:** milestones, sessions, attendance, surveys and discussions for each startup. + |- **Graduate:** stage gates are checked before a startup moves on, and it gets a certificate. + | + |## 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. + | + |It is part of the OBP-Frontend repository (`apps/cohort`). See https://cohort.tesobe.com. + |""".stripMargin) + + + glossaryItems += GlossaryItem( + title = "Conformator", + description = + s""" + |# Conformator + | + |**Conformator** lets a regulator test the open banking APIs of the banks, payment service providers and third-party providers it supervises against the agreed standard. The regulator reviews the results and issues conformance reports. + | + |The name is the Latin *conformator*, "one who shapes": the regulator sets the shape, and Conformator checks each participant's API against it. + | + |## From the rules to a signed report + | + |1. **Define:** the rules are recorded as requirements, and the tests that check each one are grouped into versioned suites. A suite's endpoints come from a standard OBP implements, or from an OpenAPI document. + |2. **Admit:** each participant is registered and given a space of its own, kept apart from everyone else's. + |3. **Test:** participants run the suites against their own non-production systems, as often as they need. + |4. **Review:** participants submit their results with evidence. Reviewers assess them, and an approver who did not assess makes the decision. Participants can ask for waivers and appeal. + |5. **Report:** approval issues a report signed with Ed25519. Anyone can check a report by its reference, without trusting the site that shows it. + | + |## 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. + |""".stripMargin) + + glossaryItems += GlossaryItem( title = "OAuth Standards and OBP", description = diff --git a/obp-api/src/main/scala/code/api/v1_2_1/Http4s121.scala b/obp-api/src/main/scala/code/api/v1_2_1/Http4s121.scala index f16df07853..d1f52f34d3 100644 --- a/obp-api/src/main/scala/code/api/v1_2_1/Http4s121.scala +++ b/obp-api/src/main/scala/code/api/v1_2_1/Http4s121.scala @@ -967,7 +967,8 @@ object Http4s121 { |${userAuthenticationMessage(true)} and the user needs to have access to the owner view.""", EmptyBody, EmptyBody, - List(AuthenticatedUserIsRequired, BankAccountNotFound, CannotRevokeOwnAccountAccess, UnknownError, "user does not have access to owner view on account"), + // UserLacksPermissionCanRevokeAccessToViewForTargetAccount: the caller cannot revoke one of the views the target user holds + List(AuthenticatedUserIsRequired, BankAccountNotFound, CannotRevokeOwnAccountAccess, UserLacksPermissionCanRevokeAccessToViewForTargetAccount, UnknownError, "user does not have access to owner view on account"), List(apiTagView, apiTagAccount, apiTagUser, apiTagOwnerRequired), http4sPartialFunction = Some(removePermissionForUserForBankAccountForAllViews) ) diff --git a/obp-api/src/main/scala/code/api/v2_2_0/Http4s220.scala b/obp-api/src/main/scala/code/api/v2_2_0/Http4s220.scala index 318b4eadec..ead03fa2c9 100644 --- a/obp-api/src/main/scala/code/api/v2_2_0/Http4s220.scala +++ b/obp-api/src/main/scala/code/api/v2_2_0/Http4s220.scala @@ -194,7 +194,8 @@ object Http4s220 { | You should use a leading _ (underscore) for the view name because other view names may become reserved by OBP internally | """, createViewJsonV121, viewJSONV220, - List(AuthenticatedUserIsRequired, InvalidJsonFormat, BankAccountNotFound, UnknownError), + // SourceViewHasLessPermission: the body asks for actions none of the caller's views on the account has + List(AuthenticatedUserIsRequired, InvalidJsonFormat, BankAccountNotFound, SourceViewHasLessPermission, UnknownError), List(apiTagAccount, apiTagView, apiTagOldStyle), None, http4sPartialFunction = Some(createViewForBankAccount)) @@ -212,6 +213,11 @@ object Http4s220 { _ <- code.util.Helper.booleanToFuture( s"${CreateCustomViewError} You need the `${CAN_CREATE_CUSTOM_VIEW}` permission on any your views", cc = Some(cc)) { anyCanCreate } + // the new view may only get actions the caller already has on one of their views of this account, else they create a view with more and grant it to themselves (as Update View and v5.1.0 check) + callerActions = permission.views.flatMap(_.allowed_actions).toSet + _ <- code.util.Helper.booleanToFuture( + s"$SourceViewHasLessPermission Current permissions of your views ($callerActions), target view permissions (${createBodyJson.allowed_actions})", + failCode = 403, cc = Some(cc)) { createBodyJson.allowed_actions.toSet.subsetOf(callerActions) } createViewJson = CreateViewJson( createBodyJson.name, createBodyJson.description, diff --git a/obp-api/src/main/scala/code/api/v5_1_0/Http4s510.scala b/obp-api/src/main/scala/code/api/v5_1_0/Http4s510.scala index f04cb1a326..9b52b8cff1 100644 --- a/obp-api/src/main/scala/code/api/v5_1_0/Http4s510.scala +++ b/obp-api/src/main/scala/code/api/v5_1_0/Http4s510.scala @@ -4453,6 +4453,11 @@ object Http4s510 { user <- Future.successful(cc.user.openOrThrowException(AuthenticatedUserIsRequired)) consent <- Future(Consents.consentProvider.vend.getConsentByConsentId(consentId)) .map(unboxFullOrFail(_, Some(cc), s"$ConsentNotFound ($consentId)", 404)) + // Only a UK Open Banking consent may be (re-)authorised here. REVOKED is also the status + // an OBP consent gets when it is revoked, so without this its owner could bring it back. + _ <- Helper.booleanToFuture(s"$ConsentDoesNotMatchStandard Required: ${Consent.ConsentStandardUK}.", 403, Some(cc)) { + Consent.assertConsentStandard(consent, Consent.ConsentStandardUK).isEmpty + } _ <- Helper.booleanToFuture(s"$ConsentStatusIssue one of ${ukReAuthableStatuses.mkString(", ")} to start SCA (current: ${consent.status}).", 400, Some(cc)) { ukReAuthableStatuses.contains(consent.status.toUpperCase) } @@ -4504,7 +4509,8 @@ object Http4s510 { |""", EmptyBody, UKConsentScaChallengeJsonV510("74a8ebda-9e5a-4c3f-9b0b-1a2b3c4d5e6f", "received", "SMS"), - List($AuthenticatedUserIsRequired, ConsentNotFound, ConsentStatusIssue, ConsentExpiredIssue, ConsentDoesNotMatchUser, InvalidConnectorResponse, UnknownError), + // ConsentDoesNotMatchStandard: only a UK Open Banking consent may start SCA here. + List($AuthenticatedUserIsRequired, ConsentNotFound, ConsentDoesNotMatchStandard, ConsentStatusIssue, ConsentExpiredIssue, ConsentDoesNotMatchUser, InvalidConnectorResponse, UnknownError), apiTagConsent :: apiTagPSD2AIS :: Nil, None, http4sPartialFunction = Some(authoriseUKConsentChallenge) @@ -4528,9 +4534,14 @@ object Http4s510 { .map(unboxFullOrFail(_, Some(cc), s"$ConsentNotFound ($consentId)", 404)) // The initial authorisation (AWAITINGAUTHORISATION) and re-authentication of an // already-authorised or dashboard-revoked (wire: CANC) consent are both allowed -- - // see ukReAuthableStatuses. EXPIRED/REJECTED are terminal. These statuses are - // UK-specific (Berlin Group uses "received", OBP uses INITIATED), so the guard also - // effectively scopes this endpoint to the UK flow. + // see ukReAuthableStatuses. EXPIRED/REJECTED are terminal. + // + // Only a UK Open Banking consent may be authorised here. An OBP consent revoked through + // the OBP revoke endpoints is REVOKED too, so the status guard alone would let its owner + // turn it back to AUTHORISED for its original consumer, without the bank. + _ <- Helper.booleanToFuture(s"$ConsentDoesNotMatchStandard Required: ${Consent.ConsentStandardUK}.", 403, Some(cc)) { + Consent.assertConsentStandard(consent, Consent.ConsentStandardUK).isEmpty + } _ <- Helper.booleanToFuture(s"$ConsentStatusIssue one of ${ukReAuthableStatuses.mkString(", ")} to be authorised (current: ${consent.status}).", 400, Some(cc)) { ukReAuthableStatuses.contains(consent.status.toUpperCase) } @@ -4667,7 +4678,8 @@ object Http4s510 { "eyJhbGciOiJIUzI1NiJ9.eyJ2aWV3cyI6W119.signature", "AUTHORISED" ), - List($AuthenticatedUserIsRequired, ConsentNotFound, ConsentStatusIssue, ConsentExpiredIssue, ConsentDoesNotMatchUser, InvalidJsonFormat, InvalidChallengeAnswer, $BankAccountNotFound, InvalidConnectorResponse, UnknownError), + // ConsentDoesNotMatchStandard: only a UK Open Banking consent may be authorised here. + List($AuthenticatedUserIsRequired, ConsentNotFound, ConsentDoesNotMatchStandard, ConsentStatusIssue, ConsentExpiredIssue, ConsentDoesNotMatchUser, InvalidJsonFormat, InvalidChallengeAnswer, $BankAccountNotFound, InvalidConnectorResponse, UnknownError), apiTagConsent :: apiTagPSD2AIS :: Nil, None, http4sPartialFunction = Some(authoriseUKConsent) 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 5b208640e0..8331b8b9ea 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 @@ -847,7 +847,8 @@ object Http4s600 { } (transactions: List[ModeratedTransaction], _) = transactionsResult moderatedTransactionsWithAttributes <- Future.sequence(transactions.map(transaction => - NewStyle.function.getTransactionAttributes(bankAccount.bankId, transaction.id, Some(cc)) + // only the attributes whose Attribute Definition lists this view, so a limited view does not see attributes meant for other views + NewStyle.function.getModeratedTransactionAttributes(bankAccount.bankId, transaction.id, view.viewId, Some(cc)) .map(attrs => code.api.v3_0_0.ModeratedTransactionWithAttributes(transaction, attrs._1)))) } yield JSONFactory600.createTransactionsJsonV600(moderatedTransactionsWithAttributes) } @@ -8232,10 +8233,9 @@ object Http4s600 { |${userAuthenticationMessage(!getProductsIsPublic)}""".stripMargin, EmptyBody, productsJsonV600, - List( - BankNotFound, - UnknownError - ), + // with apiOptions.getProductsIsPublic=false the middleware requires a login, as Lift did, so the prop can hide the catalogue + if (getProductsIsPublic) List(BankNotFound, UnknownError) + else List(AuthenticatedUserIsRequired, BankNotFound, UnknownError), apiTagProduct :: Nil, None, http4sPartialFunction = Some(getProductsV600) 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 f73477d32e..d7f20fb876 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 @@ -4401,7 +4401,10 @@ object Http4s700 { List($AuthenticatedUserIsRequired, InvalidJsonFormat, PayeeLookupIdentifierTypeNotRegistered, MobileWalletInvalidMsisdn, PayeeLookupExpiredOrNotFound, PayeeLookupMismatch, - MobileWalletDestinationNotFound, MobileWalletPaymentError, UnknownError), + MobileWalletDestinationNotFound, + // NotPositiveAmount: the connector refuses an amount that is not above zero, so a payer cannot pull money from the wallet. + NotPositiveAmount, + MobileWalletPaymentError, UnknownError), apiTagTransactionRequest :: apiTagPayee :: Nil, None, http4sPartialFunction = Some(createTransactionRequestMobileWallet) @@ -4574,7 +4577,10 @@ object Http4s700 { List($AuthenticatedUserIsRequired, InvalidJsonFormat, PayeeLookupIdentifierTypeNotRegistered, UtilityIdentifierTypeWrongCategory, UtilityInvalidIdentifier, PayeeLookupExpiredOrNotFound, PayeeLookupMismatch, - UtilityDestinationNotFound, UtilityPaymentError, UnknownError), + UtilityDestinationNotFound, + // NotPositiveAmount: the connector refuses an amount that is not above zero, so a payer cannot pull money from the biller. + NotPositiveAmount, + UtilityPaymentError, UnknownError), apiTagTransactionRequest :: apiTagPayee :: Nil, None, http4sPartialFunction = Some(createTransactionRequestUtility) @@ -4796,7 +4802,10 @@ object Http4s700 { ), List($AuthenticatedUserIsRequired, OpenCorridorDisabled, InvalidJsonFormat, InvalidJsonValue, CounterpartyBeneficiaryPermit, InvalidChargePolicy, - InsufficientAuthorisationToCreateTransactionRequest, UnknownError), + InsufficientAuthorisationToCreateTransactionRequest, + // NotPositiveAmount: the connector refuses an amount that is not above zero, so a negative promise is never netted. + NotPositiveAmount, + UnknownError), apiTagTransactionRequest :: Nil, None, http4sPartialFunction = Some(createTransactionRequestOpenCorridor) @@ -5715,6 +5724,9 @@ object Http4s700 { List($AuthenticatedUserIsRequired, InvalidJsonFormat, BulkPaymentsArrayEmpty, BulkPaymentsArrayTooLarge, BulkPaymentCurrencyMismatch, BulkDuplicateEndToEndId, + // NotPositiveAmount: an item amount that is not a number above zero refuses the batch. + // InvalidNumber: the declared total does not equal the sum of the items. + NotPositiveAmount, InvalidNumber, BulkBatchReferenceAlreadyUsed, BulkPaymentTransactionRequestError, UnknownError), apiTagTransactionRequest :: Nil, diff --git a/obp-api/src/main/scala/code/bankconnectors/LocalMappedConnector.scala b/obp-api/src/main/scala/code/bankconnectors/LocalMappedConnector.scala index ddd3bade49..d23148db4b 100644 --- a/obp-api/src/main/scala/code/bankconnectors/LocalMappedConnector.scala +++ b/obp-api/src/main/scala/code/bankconnectors/LocalMappedConnector.scala @@ -5122,7 +5122,14 @@ object LocalMappedConnector extends Connector with MdcLoggable { transactionRequestCommonBodyAmount <- NewStyle.function.tryons(s"$InvalidNumber Request Json value.amount ${transactionRequestCommonBody.value.amount} not convertible to number", 400, callContext) { BigDecimal(transactionRequestCommonBody.value.amount) } - + + // The amount must be above zero for every caller (MOBILE_WALLET, UTILITY, OPEN_CORRIDOR_PROMISE, the v4 pipeline, ...). + // A negative amount would pass the payment limit and challenge threshold checks and then move money from the destination to the caller. + isPositiveAmount = transactionRequestCommonBodyAmount > BigDecimal("0") + _ <- Helper.booleanToFuture(s"${NotPositiveAmount} Current input is: '${transactionRequestCommonBodyAmount}'", 400, callContext) { + isPositiveAmount + } + (paymentLimit, callContext) <- Connector.connector.vend.getPaymentLimit(fromAccount.bankId.value, fromAccount.accountId.value, viewId.value, transactionRequestType.value, transactionRequestCommonBody.value.currency, initiator.userId, initiator.name, callContext) map { i => (unboxFullOrFail(i._1, callContext, s"$InvalidConnectorResponseForGetPaymentLimit ", 400), i._2) } diff --git a/obp-api/src/main/scala/code/bulkpayment/BulkPaymentHandler.scala b/obp-api/src/main/scala/code/bulkpayment/BulkPaymentHandler.scala index 298caf9c80..0df889f507 100644 --- a/obp-api/src/main/scala/code/bulkpayment/BulkPaymentHandler.scala +++ b/obp-api/src/main/scala/code/bulkpayment/BulkPaymentHandler.scala @@ -82,6 +82,17 @@ object BulkPaymentHandler { _ <- Helper.booleanToFuture(BulkDuplicateEndToEndId, 400, callContext) { body.payments.map(_.end_to_end_id).distinct.size == body.payments.size } + // Every item amount must be a number above zero, as on the other transaction request endpoints. + // Each item debits the source and credits an account found by routing, so a negative amount + // would take money from an account the caller has no view on. The whole batch is refused before any payment runs. + _ <- { + val notPositive = body.payments.find(p => !scala.util.Try(BigDecimal(p.value.amount)).toOption.exists(_ > BigDecimal("0"))) + Helper.booleanToFuture( + s"$NotPositiveAmount Current input is: '${notPositive.map(_.value.amount).getOrElse("")}'", 400, callContext + ) { + notPositive.isEmpty + } + } // Total = sum of items (server-validated against caller's declared total) _ <- { val declared = BigDecimal(body.value.amount) diff --git a/obp-api/src/main/scala/code/model/BankingData.scala b/obp-api/src/main/scala/code/model/BankingData.scala index 5ad7c6e4ab..94dc1b0ece 100644 --- a/obp-api/src/main/scala/code/model/BankingData.scala +++ b/obp-api/src/main/scala/code/model/BankingData.scala @@ -287,6 +287,14 @@ case class BankAccountExtended(val bankAccount: BankAccount) extends MdcLoggable if(canRevokeAccessToAllViews(bankId, accountId, user, callContext)) for{ otherUser <- UserX.findByProviderId(otherUserProvider, otherUserIdGivenByProvider) ?~ UserNotFoundByProviderAndUsername + // the views the target user holds on this account are the ones this request removes + targetViewIds = Views.views.vend.permission(BankIdAccountId(bankId, accountId), otherUser) + .map(_.views.map(_.viewId)).getOrElse(Nil).distinct + // the caller must be able to revoke each of those views, else a caller with a custom view could remove the owner view + _ <- Helper.booleanToBox( + targetViewIds.forall(viewId => canRevokeAccessToView(bankId, accountId, viewId, user, callContext)), + UserLacksPermissionCanRevokeAccessToViewForTargetAccount + s"Current ViewIds(${targetViewIds.map(_.value).mkString(", ")}) and current UserId(${user.userId})" + ) isRevoked <- Views.views.vend.revokeAllAccountAccess(bankId, accountId, otherUser) } yield isRevoked else diff --git a/obp-api/src/test/scala/code/api/UKOpenBanking/v4_0_1/UKOpenBankingV401AccountInfoTests.scala b/obp-api/src/test/scala/code/api/UKOpenBanking/v4_0_1/UKOpenBankingV401AccountInfoTests.scala index 87f4794976..f1edbb87de 100644 --- a/obp-api/src/test/scala/code/api/UKOpenBanking/v4_0_1/UKOpenBankingV401AccountInfoTests.scala +++ b/obp-api/src/test/scala/code/api/UKOpenBanking/v4_0_1/UKOpenBankingV401AccountInfoTests.scala @@ -29,7 +29,7 @@ package code.api.UKOpenBanking.v4_0_1 import code.api.Constant import code.api.util.APIUtil.{DateWithDayFormat, ResourceDoc, buildOperationId} -import code.api.util.ErrorMessages.{ConsentDoesNotMatchConsumer, ConsentDoesNotMatchUser, ConsentExpiredIssue, ConsentIdClaimMissing, ConsentNotFound} +import code.api.util.ErrorMessages.{ConsentDoesNotMatchConsumer, ConsentDoesNotMatchStandard, ConsentDoesNotMatchUser, ConsentExpiredIssue, ConsentIdClaimMissing, ConsentNotFound} import code.api.util.{CallContext, CertificateUtil, Consent} import code.consent.{ConsentStatus, Consents} import code.model.UserExtended @@ -554,6 +554,34 @@ class UKOpenBankingV401AccountInfoTests extends UKOpenBankingV401ServerSetup { // nonce/timestamp replay check (a harness artifact -- production UK uses OAuth2 Bearer). } + // An OBP consent revoked through the OBP revoke endpoints is REVOKED, a status the UK authorise + // endpoints accept for re-authentication. Both endpoints refuse it by its standard, so its owner + // cannot turn it back to AUTHORISED. + feature("UKOB v4.0.1 the authorise endpoints act on UK consents only") { + import code.api.util.Consent + // A revoked OBP consent bound to resourceUser1, so only the standard check stands in the way. + def revokedObpConsent(): String = { + val consentId = createConsentWithStandard(Some(Consent.ConsentStandardOBP)) + Consents.consentProvider.vend.updateConsentUser(consentId, resourceUser1) + Consents.consentProvider.vend.updateConsentStatus(consentId, ConsentStatus.REVOKED) + consentId + } + scenario("challenge-start on a revoked OBP consent of the caller -> 403 ConsentDoesNotMatchStandard", UKOpenBankingV401AccountInfo) { + val consentId = revokedObpConsent() + val response = makePostRequest(scaChallengeRequest(consentId) <@ (user1), "") + response.code should equal(403) + response.body.extract[ErrorMessage].message should include(ConsentDoesNotMatchStandard) + } + scenario("authorise on a revoked OBP consent of the caller -> 403 ConsentDoesNotMatchStandard, consent stays REVOKED", UKOpenBankingV401AccountInfo) { + val consentId = revokedObpConsent() + val response = makePostRequest(authoriseRequest(consentId) <@ (user1), + s"""{"account_ids":["$acc"],"challenge_id":"any","answer":"123"}""") + response.code should equal(403) + response.body.extract[ErrorMessage].message should include(ConsentDoesNotMatchStandard) + storedConsent(consentId).status should equal(ConsentStatus.REVOKED.toString) + } + } + // Gap 15: every UK v4.0.1 response carries x-fapi-interaction-id (FAPI tracing). Uses a stub // endpoint that returns 200 so the assertion is purely about the header, independent of consent. feature("UKOB v4.0.1 x-fapi-interaction-id response header") { diff --git a/obp-api/src/test/scala/code/api/v1_2_1/API1_2_1Test.scala b/obp-api/src/test/scala/code/api/v1_2_1/API1_2_1Test.scala index a81bc8684c..44a7170928 100644 --- a/obp-api/src/test/scala/code/api/v1_2_1/API1_2_1Test.scala +++ b/obp-api/src/test/scala/code/api/v1_2_1/API1_2_1Test.scala @@ -2218,6 +2218,31 @@ class API1_2_1Test extends ServerSetupWithTestData with DefaultUsers with Privat viewsAfter should equal(viewsBefore) } + // a caller whose only view can revoke custom views must not be able to remove another user's owner view through revoke-all + scenario("a user cannot revoke all the views of another user if one of them is a view the caller cannot revoke", API1_2_1, DeletePermissions){ + Given("The caller holds only a custom view that can revoke custom views, and another user holds the owner view") + val bankId = randomBank + val bankAccount : AccountJSON = randomPrivateAccount(bankId) + val callerView = createCustomRandomView(BankId(bankId), AccountId(bankAccount.id)) + code.views.system.ViewPermission.resetViewPermissions(callerView, List(CAN_REVOKE_ACCESS_TO_CUSTOM_VIEWS)) + grantUserAccessToView(bankId, bankAccount.id, resourceUser3.idGivenByProvider, callerView.viewId.value, user1).code should equal (201) + grantUserAccessToView(bankId, bankAccount.id, resourceUser2.idGivenByProvider, SYSTEM_OWNER_VIEW_ID, user1).code should equal (201) + + When("The caller tries to revoke all the views of the other user") + val reply = revokeUserAccessToAllViews(bankId, bankAccount.id, resourceUser2.idGivenByProvider, user3) + + Then("we should get a 403 code") + reply.code should equal (403) + reply.body.extract[ErrorMessage].message should include (UserLacksPermissionCanRevokeAccessToViewForTargetAccount) + + And("The other user should still have access to the owner view") + AccountAccess.findByBankIdAccountIdViewIdUserPrimaryKey(BankId(bankId), AccountId(bankAccount.id), ViewId(SYSTEM_OWNER_VIEW_ID), resourceUser2.userPrimaryKey).isDefined should equal (true) + + //clean up: the later tests expect user2 and user3 to have no access to the test accounts + revokeUserAccessToAllViews(bankId, bankAccount.id, resourceUser2.idGivenByProvider, user1).code should equal (204) + revokeUserAccessToAllViews(bankId, bankAccount.id, resourceUser3.idGivenByProvider, user1).code should equal (204) + } + scenario("a user cannot revoke their own access to all the views on a bank account", API1_2_1, DeletePermissions){ Given("A user with access to the owner view of an account") val bankId = randomBank diff --git a/obp-api/src/test/scala/code/api/v2_2_0/API2_2_0Test.scala b/obp-api/src/test/scala/code/api/v2_2_0/API2_2_0Test.scala index c3686214b0..c2955bf053 100644 --- a/obp-api/src/test/scala/code/api/v2_2_0/API2_2_0Test.scala +++ b/obp-api/src/test/scala/code/api/v2_2_0/API2_2_0Test.scala @@ -91,7 +91,12 @@ class API2_2_0Test extends V220ServerSetup with DefaultUsers { viewsIdsToGrant } - def randomView(isPublic: Boolean, alias: String) = createViewJsonV300.toCreateViewJson + // only the actions of the owner view user1 holds, as Create View refuses actions none of the caller's views has + def randomView(isPublic: Boolean, alias: String) = { + val view = createViewJsonV300.toCreateViewJson + val ownerActions = (SYSTEM_OWNER_VIEW_PERMISSION_ADMIN ++ SYSTEM_VIEW_PERMISSION_COMMON).toSet + view.copy(allowed_actions = view.allowed_actions.filter(ownerActions.contains)) + } def getBanksInfo : APIResponse = { @@ -274,7 +279,21 @@ class API2_2_0Test extends V220ServerSetup with DefaultUsers { And("we should get an error message") reply.body.extract[ErrorMessage].message.nonEmpty should equal (true) } - + + // the new view may only get actions the caller already has on one of their views of the account + scenario("We will not create a view with an action that none of the caller's views has", API2_2, ApiEndpoint2) { + Given("We will use an access token") + val bankId = randomBank + val bankAccountId = randomPrivateAccountId(bankId) + val view = randomView(true, "") + When("we ask for an action that no view of the caller has") + val reply = postView(bankId, bankAccountId, + view.copy(allowed_actions = view.allowed_actions :+ "can_do_what_no_view_of_the_caller_can"), user1) + Then("we should get a 403 and the SourceViewHasLessPermission message") + reply.code should equal (403) + reply.body.extract[ErrorMessage].message should startWith (code.api.util.ErrorMessages.SourceViewHasLessPermission) + } + scenario("can not create the System View") { Given("The BANK_ID, ACCOUNT_ID, Login user, views") val bankId = randomBankId diff --git a/obp-api/src/test/scala/code/api/v6_0_0/ProductsV600Test.scala b/obp-api/src/test/scala/code/api/v6_0_0/ProductsV600Test.scala new file mode 100644 index 0000000000..f8a0e3bd36 --- /dev/null +++ b/obp-api/src/test/scala/code/api/v6_0_0/ProductsV600Test.scala @@ -0,0 +1,71 @@ +/** +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.AuthenticatedUserIsRequired +import code.api.v6_0_0.Http4s600.Implementations6_0_0 +import code.setup.DefaultUsers +import com.github.dwickern.macros.NameOf.nameOf +import com.openbankproject.commons.model.ErrorMessage +import com.openbankproject.commons.util.ApiVersion +import org.scalatest.Tag + +class ProductsV600Test extends V600ServerSetup with DefaultUsers { + + object VersionOfApi extends Tag(ApiVersion.v6_0_0.toString) + object ApiEndpoint1 extends Tag(nameOf(Implementations6_0_0.getProductsV600)) + + feature(s"Assuring that endpoint getProductsV600 honours apiOptions.getProductsIsPublic - $VersionOfApi") { + + // with apiOptions.getProductsIsPublic=false the product list refuses anonymous callers with 401; the prop is read once at startup, so this JVM sees only one branch + scenario("We get the products without user credentials", ApiEndpoint1, VersionOfApi) { + When("We get the products with no authentication") + val request = (v6_0_0_Request / "banks" / testBankId1.value / "products").GET + val response = makeGetRequest(request) + if (code.api.util.APIUtil.getProductsIsPublic) { + Then("We should get a 200") + response.code should equal(200) + } else { + Then("We should get a 401") + response.code should equal(401) + And("error should be " + AuthenticatedUserIsRequired) + response.body.extract[ErrorMessage].message should equal(AuthenticatedUserIsRequired) + } + } + + // a logged-in caller gets the product list whatever the prop says + scenario("We get the products with user credentials", ApiEndpoint1, VersionOfApi) { + When("We get the products as user1") + val request = (v6_0_0_Request / "banks" / testBankId1.value / "products").GET <@ (user1) + val response = makeGetRequest(request) + Then("We should get a 200") + response.code should equal(200) + } + } +} diff --git a/obp-api/src/test/scala/code/api/v6_0_0/TransactionsForBankAccountTest.scala b/obp-api/src/test/scala/code/api/v6_0_0/TransactionsForBankAccountTest.scala new file mode 100644 index 0000000000..c6106ce323 --- /dev/null +++ b/obp-api/src/test/scala/code/api/v6_0_0/TransactionsForBankAccountTest.scala @@ -0,0 +1,90 @@ +/** +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.Constant.SYSTEM_OWNER_VIEW_ID +import code.api.attributedefinition.AttributeDefinitionDI +import code.api.util.APIUtil +import code.api.util.APIUtil.OAuth._ +import code.api.v6_0_0.Http4s600.Implementations6_0_0 +import code.transactionattribute.TransactionAttributeX +import com.github.dwickern.macros.NameOf.nameOf +import com.openbankproject.commons.model.{BankId, TransactionId} +import com.openbankproject.commons.model.enums.{AttributeCategory, AttributeType, TransactionAttributeType} +import com.openbankproject.commons.util.ApiVersion +import org.scalatest.Tag + +import scala.concurrent.Await +import scala.concurrent.duration._ + +class TransactionsForBankAccountTest extends V600ServerSetup { + + // this suite reads the transactions created before each scenario + override protected def needsTransactionData: Boolean = true + + object VersionOfApi extends Tag(ApiVersion.v6_0_0.toString) + object ApiEndpoint1 extends Tag(nameOf(Implementations6_0_0.getTransactionsForBankAccount)) + + feature(s"Get Transactions for Account - $VersionOfApi") { + + // an attribute is shown on a view only when its Attribute Definition lists that view + scenario("Only attributes defined as seen on the view are returned", ApiEndpoint1, VersionOfApi) { + val bankId = testBankId1.value + val accountId = testAccountId1.value + val request = (v6_0_0_Request / "banks" / bankId / "accounts" / accountId / SYSTEM_OWNER_VIEW_ID / "transactions").GET <@ (user1) + + Given("a transaction on the account") + val before = makeGetRequest(request) + before.code should equal(200) + val transactionId = before.body.extract[TransactionsJsonV600].transactions.head.transaction_id + + And("two attributes on it, one defined as seen on another view, one on the owner view") + val hiddenName = "HIDDEN_" + APIUtil.generateUUID().take(8) + val shownName = "SHOWN_" + APIUtil.generateUUID().take(8) + Await.result(AttributeDefinitionDI.attributeDefinition.vend.createOrUpdateAttributeDefinition( + BankId(bankId), hiddenName, AttributeCategory.Transaction, AttributeType.STRING, "", "", List("accountant"), true), 10.seconds) + Await.result(AttributeDefinitionDI.attributeDefinition.vend.createOrUpdateAttributeDefinition( + BankId(bankId), shownName, AttributeCategory.Transaction, AttributeType.STRING, "", "", List(SYSTEM_OWNER_VIEW_ID), true), 10.seconds) + Await.result(TransactionAttributeX.transactionAttributeProvider.vend.createOrUpdateTransactionAttribute( + BankId(bankId), TransactionId(transactionId), None, hiddenName, TransactionAttributeType.STRING, "secret"), 10.seconds) + Await.result(TransactionAttributeX.transactionAttributeProvider.vend.createOrUpdateTransactionAttribute( + BankId(bankId), TransactionId(transactionId), None, shownName, TransactionAttributeType.STRING, "visible"), 10.seconds) + + When("we get the transactions through the owner view") + val response = makeGetRequest(request) + + Then("we get a 200 with only the attribute defined for the owner view") + response.code should equal(200) + val transaction = response.body.extract[TransactionsJsonV600].transactions.find(_.transaction_id == transactionId) + transaction.isDefined should equal(true) + val attributeNames = transaction.get.transaction_attributes.map(_.name) + attributeNames should contain (shownName) + attributeNames should not contain (hiddenName) + } + } +} diff --git a/obp-api/src/test/scala/code/api/v7_0_0/Http4s700RoutesTest.scala b/obp-api/src/test/scala/code/api/v7_0_0/Http4s700RoutesTest.scala index 8893c26277..ca4540db8b 100644 --- a/obp-api/src/test/scala/code/api/v7_0_0/Http4s700RoutesTest.scala +++ b/obp-api/src/test/scala/code/api/v7_0_0/Http4s700RoutesTest.scala @@ -35,7 +35,7 @@ import code.api.Constant.SYSTEM_OWNER_VIEW_ID import code.api.ResponseHeader import code.api.util.APIUtil import code.api.util.ApiRole.{canAttachOpenCorridorPromise, canConfigureAmqpBankBroker, canGetMessageOutbox, canRetryMessageOutbox, canSettleOpenCorridor, canCreateAccount, canCreateEntitlementAtAnyBank, canCreateTenant, canCreateRoutingScheme, canCreateUtilityVendResult, canDeleteAccountNotificationWebhookAtOneBank, canDeleteEntitlementAtAnyBank, canDeleteTenant, canDeleteRoutingScheme, canDeleteSchedulerJobLock, canDeleteSystemAccountNotificationWebhook, canUpdateSystemView, canGetAccountAccessTrace, canGetAccountDirectoryAtOneBank, canGetTenant, canGetAnyUser, canGetCacheConfig, canGetCacheInfo, canGetCacheNamespaces, canGetCardsForBank, canGetConnectorHealth, canCreateMetricsArchiveRun, canGetCustomersAtOneBank, canGetDatabasePoolInfo, canGetMetricsDiagnostics, canGetMigrations, canGetSchedulerJobLocks, canReadResourceDoc, canUpdateBankSupportedRoutingScheme, canUpdateTenant, canUpdateRoutingScheme} -import code.api.util.ErrorMessages.{AccountIdAlreadyExists, AuthenticatedUserIsRequired, BankNotFound, DuplicateUsername, EntitlementAlreadyExists, InvalidAccountRoutings, InvalidJsonFormat, InvalidJsonValue, InvalidTenantIdFormat, InvalidPhoneNumber, InvalidRoutingSchemeName, UserFilterParametersNotSupported, InvalidTransactionRequestId, MessageOutboxRowNotFound, MessageOutboxRowNotSticky, MobileWalletDestinationNotFound, MobileWalletInvalidMsisdn, NotificationWebhookNotFound, AmqpBankBrokerNotConfigured, OpenCorridorDisabled, OpenCorridorPromiseEvidenceConflict, OpenCorridorPromiseNotPending, OpenCorridorPromiseTypeMismatch, OpenCorridorSameBankNotAllowed, OpenCorridorSettlementAddressMissing, OpenCorridorSettlementNotFound, TenantAlreadyExists, TenantNotFound, PayeeLookupAddressMismatch, PayeeLookupIdentifierTypeNotRegistered, PayeeNotFound, RoutingSchemeAlreadyExists, RoutingSchemeExampleAddressMismatch, RoutingSchemeNotFound, SelfServiceBankCreationDisabled, SelfServiceBankLimitReached, SystemViewNotFound, UserHasMissingRoles, UserNotFoundByUserId, UtilityIdentifierTypeWrongCategory, UtilityInvalidIdentifier, UtilityTransactionRequestNotFound} +import code.api.util.ErrorMessages.{NotPositiveAmount, AccountIdAlreadyExists,AuthenticatedUserIsRequired, BankNotFound, DuplicateUsername, EntitlementAlreadyExists, InvalidAccountRoutings, InvalidJsonFormat, InvalidJsonValue, InvalidTenantIdFormat, InvalidPhoneNumber, InvalidRoutingSchemeName, UserFilterParametersNotSupported, InvalidTransactionRequestId, MessageOutboxRowNotFound, MessageOutboxRowNotSticky, MobileWalletDestinationNotFound, MobileWalletInvalidMsisdn, NotificationWebhookNotFound, AmqpBankBrokerNotConfigured, OpenCorridorDisabled, OpenCorridorPromiseEvidenceConflict, OpenCorridorPromiseNotPending, OpenCorridorPromiseTypeMismatch, OpenCorridorSameBankNotAllowed, OpenCorridorSettlementAddressMissing, OpenCorridorSettlementNotFound, TenantAlreadyExists, TenantNotFound, PayeeLookupAddressMismatch, PayeeLookupIdentifierTypeNotRegistered, PayeeNotFound, RoutingSchemeAlreadyExists, RoutingSchemeExampleAddressMismatch, RoutingSchemeNotFound, SelfServiceBankCreationDisabled, SelfServiceBankLimitReached, SystemViewNotFound, UserHasMissingRoles, UserNotFoundByUserId, UtilityIdentifierTypeWrongCategory, UtilityInvalidIdentifier, UtilityTransactionRequestNotFound} import code.utilitypayment.{UtilityCallbackStatus, UtilityPaymentCallbacks} import code.scheduler.JobScheduler import net.liftweb.mapper.By @@ -2728,6 +2728,44 @@ class Http4s700RoutesTest extends ServerSetupWithTestData { case _ => fail("Expected JSON object") } } + + // A negative amount is refused with 400 NotPositiveAmount, so a payer cannot pull money out of a wallet it names by phone number. + scenario("Return 400 NotPositiveAmount when value.amount is negative", Http4s700RoutesTag) { + val bankId = testBankId1.value + val accountId = testAccountId0.value + // Register XN.MSISDN and route a fresh MSISDN to a wallet at the other bank, so the destination resolves. + val country = "XN" + val schemeName = s"$country.MSISDN" + RoutingSchemes.routingScheme.vend.getRoutingScheme(schemeName) match { + case net.liftweb.common.Full(_) => // already registered from a previous run + case _ => + RoutingSchemes.routingScheme.vend.createRoutingScheme( + scheme = schemeName, country = country, category = "ACCOUNT", + addressPattern = "^[0-9]+$", secondaryAddressPattern = None, + exampleAddress = "255778300336", description = "Test only", + downstreamRails = Nil, status = "ACTIVE", createdByUserId = resourceUser1.userId + ) + } + val msisdn = "9" + System.nanoTime().toString.takeRight(11) + BankAccountRouting.create + .BankId(testBankId2.value) + .AccountId(testAccountId1.value) + .AccountRoutingScheme(schemeName) + .AccountRoutingAddress(msisdn) + .saveMe() + val body = s"""{"to":{"msisdn":"$msisdn"},"value":{"currency":"EUR","amount":"-1000"},"description":"x","country_code":"$country"}""" + val headers = Map("DirectLogin" -> s"token=${token1.value}") + val (statusCode, json, _) = makeHttpRequestWithBody("POST", s"/obp/v7.0.0/banks/$bankId/accounts/$accountId/owner/transaction-request-types/MOBILE_WALLET/transaction-requests", body, headers) + statusCode shouldBe 400 + json match { + case JObject(fields) => + toFieldMap(fields).get("message") match { + case Some(JString(msg)) => msg should include(NotPositiveAmount) + case _ => fail("Expected message field") + } + case _ => fail("Expected JSON object") + } + } } // ─── OPEN_CORRIDOR_PROMISE transaction request ──────────────────────────── @@ -3941,6 +3979,64 @@ class Http4s700RoutesTest extends ServerSetupWithTestData { } } + // A negative item amount would move money from the routed destination to the source account, + // so the batch is refused with 400 NotPositiveAmount before any payment runs. + scenario("Return 400 when an item amount is negative", Http4s700RoutesTag) { + val bankId = testBankId1.value + val accountId = testAccountId0.value + val acctCurrency = code.bankconnectors.Connector.connector.vend + .getBankAccountLegacy(testBankId1, testAccountId0, None) + .map(_._1.currency).openOrThrowException("test account") + val body = + s"""{ + | "batch_reference": "${freshBatchReference()}", + | "payments": [{"end_to_end_id":"E1","to_account_routing":{"scheme":"TZ.BANK_ACCOUNT","address":"123"},"value":{"currency":"$acctCurrency","amount":"-100.00"},"description":"x"}], + | "value": {"currency":"$acctCurrency","amount":"-100.00"}, + | "description": "negative amount" + |}""".stripMargin + val headers = Map("DirectLogin" -> s"token=${token1.value}") + val (statusCode, json, _) = makeHttpRequestWithBody("POST", s"/obp/v7.0.0/banks/$bankId/accounts/$accountId/owner/transaction-request-types/BULK/transaction-requests", body, headers) + statusCode shouldBe 400 + json match { + case JObject(fields) => + toFieldMap(fields).get("message") match { + case Some(JString(msg)) => msg should include(code.api.util.ErrorMessages.NotPositiveAmount) + case _ => fail("Expected message field") + } + case _ => fail("Expected JSON object") + } + } + + // A zero item amount is refused the same way, since only amounts above zero are payments. + scenario("Return 400 when an item amount is zero", Http4s700RoutesTag) { + val bankId = testBankId1.value + val accountId = testAccountId0.value + val acctCurrency = code.bankconnectors.Connector.connector.vend + .getBankAccountLegacy(testBankId1, testAccountId0, None) + .map(_._1.currency).openOrThrowException("test account") + val body = + s"""{ + | "batch_reference": "${freshBatchReference()}", + | "payments": [ + | {"end_to_end_id":"E1","to_account_routing":{"scheme":"TZ.BANK_ACCOUNT","address":"123"},"value":{"currency":"$acctCurrency","amount":"1.00"},"description":"x"}, + | {"end_to_end_id":"E2","to_account_routing":{"scheme":"TZ.BANK_ACCOUNT","address":"124"},"value":{"currency":"$acctCurrency","amount":"0"},"description":"y"} + | ], + | "value": {"currency":"$acctCurrency","amount":"1.00"}, + | "description": "zero amount" + |}""".stripMargin + val headers = Map("DirectLogin" -> s"token=${token1.value}") + val (statusCode, json, _) = makeHttpRequestWithBody("POST", s"/obp/v7.0.0/banks/$bankId/accounts/$accountId/owner/transaction-request-types/BULK/transaction-requests", body, headers) + statusCode shouldBe 400 + json match { + case JObject(fields) => + toFieldMap(fields).get("message") match { + case Some(JString(msg)) => msg should include(code.api.util.ErrorMessages.NotPositiveAmount) + case _ => fail("Expected message field") + } + case _ => fail("Expected JSON object") + } + } + scenario("Return 409 when batch_reference is reused on the same source account", Http4s700RoutesTag) { val bankId = testBankId1.value val accountId = testAccountId0.value diff --git a/scripts/resource_doc_baseline/parity_allowlist.json b/scripts/resource_doc_baseline/parity_allowlist.json index becfe19105..3f992f1b27 100644 --- a/scripts/resource_doc_baseline/parity_allowlist.json +++ b/scripts/resource_doc_baseline/parity_allowlist.json @@ -139,6 +139,14 @@ "lift_digest": "23846b4ba3c1ae811448bcfeef69c445790d7d138dccac8f929e415f3a250f74", "http4s_digest": "5a8117168f16e523c860e789cdfc5969a95c43e163cf170dbaae992f6e7bbb6b" }, + { + "version": "v6_0_0", + "endpoint": "getProductsV600", + "field": "errorResponseBodies", + "reason": "AuthenticatedUserIsRequired is added when apiOptions.getProductsIsPublic=false, so the middleware requires a login as the Lift code did with authenticatedAccess", + "lift_digest": "3bdcd0c958443de6b8a40314fb0e25bb976e6a734c73b4877302491756cb2ab9", + "http4s_digest": "ff19d358f83b960a52f9fbdd96a02ddd930feef41ad37737d3c812fe99f72c7b" + }, { "version": "v4_0_0", "endpoint": "getAtms", @@ -255,9 +263,9 @@ "version": "v1_2_1", "endpoint": "removePermissionForUserForBankAccountForAllViews", "field": "errorResponseBodies", - "reason": "Added CannotRevokeOwnAccountAccess (403): a user cannot revoke their own access to all views", + "reason": "Added CannotRevokeOwnAccountAccess (403): a user cannot revoke their own access to all views. Added UserLacksPermissionCanRevokeAccessToViewForTargetAccount (403): the caller must be able to revoke each view the target user holds", "lift_digest": "b72cefb915c6af0190e4543aed820722db264a43a54247247d9a1fdb25321703", - "http4s_digest": "1504d43b14defdedbab99f5784e36dbc7d3c6e1eca29fddc41d81f43d3ae0bcd" + "http4s_digest": "8fc3bece8cf4d5a977125fd6e97ca3feee5d8730a8fb0942e35c337591fc5ddd" }, { "version": "v4_0_0", @@ -715,6 +723,14 @@ "lift_digest": "91d541e4991471ff3b872dabd9b68fe6bc29b979fc91df495643a3bd361c0d60", "http4s_digest": "69ccaef44e7ddda887462c6431f0ffe7b0f0a4a91f4e12bb5f207dffb3d3dc20" }, + { + "version": "v2_2_0", + "endpoint": "createViewForBankAccount", + "field": "errorResponseBodies", + "reason": "Added SourceViewHasLessPermission: Create View refuses (403) a view whose allowed_actions are not all on one of the caller's views of the account, as Update View does", + "lift_digest": "63c2f1b01e07eb8a86158e5631bde4dd32465aa75c13ba61d369f0ad8cf952d7", + "http4s_digest": "0f50f78378cc09491986f9a9ee074ebd5d56b93debc411788c9c453db54b623d" + }, { "version": "v2_2_0", "endpoint": "updateViewForBankAccount",