From 128595cdb052e79c725aad0042cb674497edfae8 Mon Sep 17 00:00:00 2001 From: karmaking Date: Tue, 13 Jan 2026 14:45:22 +0100 Subject: [PATCH 1/8] fix github action --- .github/workflows/auto_update_base_image.yml | 35 ---- .../build_container_develop_branch.yml | 30 ---- .../build_container_non_develop_branch.yml | 151 ------------------ .github/workflows/build_pull_request.yml | 124 -------------- .github/workflows/run_trivy.yml | 54 ------- .gitignore | 1 - 6 files changed, 395 deletions(-) delete mode 100644 .github/workflows/auto_update_base_image.yml delete mode 100644 .github/workflows/build_container_non_develop_branch.yml delete mode 100644 .github/workflows/build_pull_request.yml delete mode 100644 .github/workflows/run_trivy.yml diff --git a/.github/workflows/auto_update_base_image.yml b/.github/workflows/auto_update_base_image.yml deleted file mode 100644 index 3048faf15e..0000000000 --- a/.github/workflows/auto_update_base_image.yml +++ /dev/null @@ -1,35 +0,0 @@ -name: Regular base image update check -on: - schedule: - - cron: "0 5 * * *" - workflow_dispatch: - -env: - ## Sets environment variable - DOCKER_HUB_ORGANIZATION: ${{ vars.DOCKER_HUB_ORGANIZATION }} - -jobs: - build: - runs-on: ubuntu-latest - steps: - - name: Checkout repository - uses: actions/checkout@v4 - - - name: Docker Image Update Checker - id: baseupdatecheck - uses: lucacome/docker-image-update-checker@v2.0.0 - with: - base-image: jetty:9.4-jdk11-alpine - image: ${{ env.DOCKER_HUB_ORGANIZATION }}/obp-api:latest - - - name: Trigger build_container_develop_branch workflow - uses: actions/github-script@v6 - with: - script: | - await github.rest.actions.createWorkflowDispatch({ - owner: context.repo.owner, - repo: context.repo.repo, - workflow_id: 'build_container_develop_branch.yml', - ref: 'refs/heads/develop' - }); - if: steps.baseupdatecheck.outputs.needs-updating == 'true' diff --git a/.github/workflows/build_container_develop_branch.yml b/.github/workflows/build_container_develop_branch.yml index 3afc3d6ec5..db6bd51602 100644 --- a/.github/workflows/build_container_develop_branch.yml +++ b/.github/workflows/build_container_develop_branch.yml @@ -124,33 +124,3 @@ jobs: with: name: ${{ github.sha }} path: push/ - - - name: Build the Docker image - run: | - echo "${{ secrets.DOCKER_HUB_TOKEN }}" | docker login -u "${{ secrets.DOCKER_HUB_USERNAME }}" --password-stdin docker.io - docker build . --file .github/Dockerfile_PreBuild --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:$GITHUB_SHA --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:latest --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:develop - docker build . --file .github/Dockerfile_PreBuild_OC --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:$GITHUB_SHA-OC --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:latest-OC --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:develop-OC --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:${GITHUB_REF##*/}-OC - docker push docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }} --all-tags - echo docker done - - - uses: sigstore/cosign-installer@4d14d7f17e7112af04ea6108fbb4bfc714c00390 - - - name: Write signing key to disk (only needed for `cosign sign --key`) - run: echo "${{ secrets.COSIGN_PRIVATE_KEY }}" > cosign.key - - - name: Sign container image - run: | - cosign sign -y --key cosign.key \ - docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:develop - cosign sign -y --key cosign.key \ - docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:latest - cosign sign -y --key cosign.key \ - docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:$GITHUB_SHA - cosign sign -y --key cosign.key \ - docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:develop-OC - cosign sign -y --key cosign.key \ - docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:latest-OC - env: - COSIGN_PASSWORD: "${{secrets.COSIGN_PASSWORD}}" - - diff --git a/.github/workflows/build_container_non_develop_branch.yml b/.github/workflows/build_container_non_develop_branch.yml deleted file mode 100644 index fda13bb721..0000000000 --- a/.github/workflows/build_container_non_develop_branch.yml +++ /dev/null @@ -1,151 +0,0 @@ -name: Build and publish container non develop - -on: - push: - branches: - - '**' - - '!develop' - -env: - DOCKER_HUB_ORGANIZATION: ${{ vars.DOCKER_HUB_ORGANIZATION }} - DOCKER_HUB_REPOSITORY: obp-api - -jobs: - build: - runs-on: ubuntu-latest - services: - # Label used to access the service container - redis: - # Docker Hub image - image: redis - ports: - # Opens tcp port 6379 on the host and service container - - 6379:6379 - # Set health checks to wait until redis has started - options: >- - --health-cmd "redis-cli ping" - --health-interval 10s - --health-timeout 5s - --health-retries 5 - steps: - - uses: actions/checkout@v4 - - name: Extract branch name - shell: bash - run: echo "branch=${GITHUB_HEAD_REF:-${GITHUB_REF#refs/heads/}}" - - name: Set up JDK 11 - uses: actions/setup-java@v4 - with: - java-version: '11' - distribution: 'adopt' - cache: maven - - name: Build with Maven - run: | - set -o pipefail - cp obp-api/src/main/resources/props/sample.props.template obp-api/src/main/resources/props/production.default.props - echo connector=star > obp-api/src/main/resources/props/test.default.props - echo starConnector_supported_types=mapped,internal >> obp-api/src/main/resources/props/test.default.props - echo hostname=http://localhost:8016 >> obp-api/src/main/resources/props/test.default.props - echo tests.port=8016 >> obp-api/src/main/resources/props/test.default.props - echo End of minimum settings >> obp-api/src/main/resources/props/test.default.props - echo payments_enabled=false >> obp-api/src/main/resources/props/test.default.props - echo importer_secret=change_me >> obp-api/src/main/resources/props/test.default.props - echo messageQueue.updateBankAccountsTransaction=false >> obp-api/src/main/resources/props/test.default.props - echo messageQueue.createBankAccounts=false >> obp-api/src/main/resources/props/test.default.props - echo allow_sandbox_account_creation=true >> obp-api/src/main/resources/props/test.default.props - echo allow_sandbox_data_import=true >> obp-api/src/main/resources/props/test.default.props - echo sandbox_data_import_secret=change_me >> obp-api/src/main/resources/props/test.default.props - echo allow_account_deletion=true >> obp-api/src/main/resources/props/test.default.props - echo allowed_internal_redirect_urls = /,/oauth/authorize >> obp-api/src/main/resources/props/test.default.props - echo transactionRequests_enabled=true >> obp-api/src/main/resources/props/test.default.props - echo transactionRequests_supported_types=SEPA,SANDBOX_TAN,FREE_FORM,COUNTERPARTY,ACCOUNT,SIMPLE >> obp-api/src/main/resources/props/test.default.props - echo SIMPLE_OTP_INSTRUCTION_TRANSPORT=dummy >> obp-api/src/main/resources/props/test.default.props - echo openredirects.hostname.whitlelist=http://127.0.0.1,http://localhost >> obp-api/src/main/resources/props/test.default.props - echo remotedata.secret = foobarbaz >> obp-api/src/main/resources/props/test.default.props - echo allow_public_views=true >> obp-api/src/main/resources/props/test.default.props - - echo SIMPLE_OTP_INSTRUCTION_TRANSPORT=dummy >> obp-api/src/main/resources/props/test.default.props - echo ACCOUNT_OTP_INSTRUCTION_TRANSPORT=dummy >> obp-api/src/main/resources/props/test.default.props - echo SEPA_OTP_INSTRUCTION_TRANSPORT=dummy >> obp-api/src/main/resources/props/test.default.props - echo FREE_FORM_OTP_INSTRUCTION_TRANSPORT=dummy >> obp-api/src/main/resources/props/test.default.props - echo COUNTERPARTY_OTP_INSTRUCTION_TRANSPORT=dummy >> obp-api/src/main/resources/props/test.default.props - echo SEPA_CREDIT_TRANSFERS_OTP_INSTRUCTION_TRANSPORT=dummy >> obp-api/src/main/resources/props/test.default.props - - echo allow_oauth2_login=true >> obp-api/src/main/resources/props/test.default.props - echo oauth2.jwk_set.url=https://www.googleapis.com/oauth2/v3/certs >> obp-api/src/main/resources/props/test.default.props - - echo ResetPasswordUrlEnabled=true >> obp-api/src/main/resources/props/test.default.props - - echo consents.allowed=true >> obp-api/src/main/resources/props/test.default.props - MAVEN_OPTS="-Xmx3G -Xss2m" mvn clean package -Pprod 2>&1 | tee maven-build.log - - - name: Report failing tests (if any) - if: always() - run: | - echo "Checking build log for failing tests via grep..." - if [ ! -f maven-build.log ]; then - echo "No maven-build.log found; skipping failure scan." - exit 0 - fi - if grep -n "\*\*\* FAILED \*\*\*" maven-build.log; then - echo "Failing tests detected above." - exit 1 - else - echo "No failing tests detected in maven-build.log." - fi - - - name: Upload Maven build log - if: always() - uses: actions/upload-artifact@v4 - with: - name: maven-build-log - if-no-files-found: ignore - path: | - maven-build.log - - - name: Upload test reports - if: always() - uses: actions/upload-artifact@v4 - with: - name: test-reports - if-no-files-found: ignore - path: | - obp-api/target/surefire-reports/** - obp-commons/target/surefire-reports/** - **/target/scalatest-reports/** - **/target/site/surefire-report.html - **/target/site/surefire-report/* - - - name: Save .war artifact - run: | - mkdir -p ./push - cp obp-api/target/obp-api-1.*.war ./push/ - - uses: actions/upload-artifact@v4 - with: - name: ${{ github.sha }} - path: push/ - - - name: Build the Docker image - run: | - echo "${{ secrets.DOCKER_HUB_TOKEN }}" | docker login -u "${{ secrets.DOCKER_HUB_USERNAME }}" --password-stdin docker.io - docker build . --file .github/Dockerfile_PreBuild --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:$GITHUB_SHA --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:${GITHUB_REF##*/} - docker build . --file .github/Dockerfile_PreBuild_OC --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:$GITHUB_SHA-OC --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:${GITHUB_REF##*/}-OC - docker push docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }} --all-tags - echo docker done - - - uses: sigstore/cosign-installer@4d14d7f17e7112af04ea6108fbb4bfc714c00390 - - - name: Write signing key to disk (only needed for `cosign sign --key`) - run: echo "${{ secrets.COSIGN_PRIVATE_KEY }}" > cosign.key - - - name: Sign container image - run: | - cosign sign -y --key cosign.key \ - docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:${GITHUB_REF##*/} - cosign sign -y --key cosign.key \ - docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:${GITHUB_REF##*/}-OC - cosign sign -y --key cosign.key \ - docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:$GITHUB_SHA - env: - COSIGN_PASSWORD: "${{secrets.COSIGN_PASSWORD}}" - - diff --git a/.github/workflows/build_pull_request.yml b/.github/workflows/build_pull_request.yml deleted file mode 100644 index 61d1e05a5a..0000000000 --- a/.github/workflows/build_pull_request.yml +++ /dev/null @@ -1,124 +0,0 @@ -name: Build on Pull Request - -on: - pull_request: - branches: - - '**' -env: - ## Sets environment variable - DOCKER_HUB_ORGANIZATION: ${{ vars.DOCKER_HUB_ORGANIZATION }} - - -jobs: - build: - runs-on: ubuntu-latest - services: - # Label used to access the service container - redis: - # Docker Hub image - image: redis - ports: - # Opens tcp port 6379 on the host and service container - - 6379:6379 - # Set health checks to wait until redis has started - options: >- - --health-cmd "redis-cli ping" - --health-interval 10s - --health-timeout 5s - --health-retries 5 - steps: - - uses: actions/checkout@v4 - - name: Set up JDK 11 - uses: actions/setup-java@v4 - with: - java-version: '11' - distribution: 'adopt' - cache: maven - - name: Build with Maven - run: | - set -o pipefail - cp obp-api/src/main/resources/props/sample.props.template obp-api/src/main/resources/props/production.default.props - echo connector=star > obp-api/src/main/resources/props/test.default.props - echo starConnector_supported_types=mapped,internal >> obp-api/src/main/resources/props/test.default.props - echo hostname=http://localhost:8016 >> obp-api/src/main/resources/props/test.default.props - echo tests.port=8016 >> obp-api/src/main/resources/props/test.default.props - echo End of minimum settings >> obp-api/src/main/resources/props/test.default.props - echo payments_enabled=false >> obp-api/src/main/resources/props/test.default.props - echo importer_secret=change_me >> obp-api/src/main/resources/props/test.default.props - echo messageQueue.updateBankAccountsTransaction=false >> obp-api/src/main/resources/props/test.default.props - echo messageQueue.createBankAccounts=false >> obp-api/src/main/resources/props/test.default.props - echo allow_sandbox_account_creation=true >> obp-api/src/main/resources/props/test.default.props - echo allow_sandbox_data_import=true >> obp-api/src/main/resources/props/test.default.props - echo sandbox_data_import_secret=change_me >> obp-api/src/main/resources/props/test.default.props - echo allow_account_deletion=true >> obp-api/src/main/resources/props/test.default.props - echo allowed_internal_redirect_urls = /,/oauth/authorize >> obp-api/src/main/resources/props/test.default.props - echo transactionRequests_enabled=true >> obp-api/src/main/resources/props/test.default.props - echo transactionRequests_supported_types=SEPA,SANDBOX_TAN,FREE_FORM,COUNTERPARTY,ACCOUNT,SIMPLE >> obp-api/src/main/resources/props/test.default.props - echo SIMPLE_OTP_INSTRUCTION_TRANSPORT=dummy >> obp-api/src/main/resources/props/test.default.props - echo openredirects.hostname.whitlelist=http://127.0.0.1,http://localhost >> obp-api/src/main/resources/props/test.default.props - echo remotedata.secret = foobarbaz >> obp-api/src/main/resources/props/test.default.props - echo allow_public_views=true >> obp-api/src/main/resources/props/test.default.props - - echo SIMPLE_OTP_INSTRUCTION_TRANSPORT=dummy >> obp-api/src/main/resources/props/test.default.props - echo ACCOUNT_OTP_INSTRUCTION_TRANSPORT=dummy >> obp-api/src/main/resources/props/test.default.props - echo SEPA_OTP_INSTRUCTION_TRANSPORT=dummy >> obp-api/src/main/resources/props/test.default.props - echo FREE_FORM_OTP_INSTRUCTION_TRANSPORT=dummy >> obp-api/src/main/resources/props/test.default.props - echo COUNTERPARTY_OTP_INSTRUCTION_TRANSPORT=dummy >> obp-api/src/main/resources/props/test.default.props - echo SEPA_CREDIT_TRANSFERS_OTP_INSTRUCTION_TRANSPORT=dummy >> obp-api/src/main/resources/props/test.default.props - - echo allow_oauth2_login=true >> obp-api/src/main/resources/props/test.default.props - echo oauth2.jwk_set.url=https://www.googleapis.com/oauth2/v3/certs >> obp-api/src/main/resources/props/test.default.props - - echo ResetPasswordUrlEnabled=true >> obp-api/src/main/resources/props/test.default.props - - echo consents.allowed=true >> obp-api/src/main/resources/props/test.default.props - MAVEN_OPTS="-Xmx3G -Xss2m" mvn clean package -Pprod 2>&1 | tee maven-build.log - - - name: Report failing tests (if any) - if: always() - run: | - echo "Checking build log for failing tests via grep..." - if [ ! -f maven-build.log ]; then - echo "No maven-build.log found; skipping failure scan." - exit 0 - fi - if grep -n "\*\*\* FAILED \*\*\*" maven-build.log; then - echo "Failing tests detected above." - exit 1 - else - echo "No failing tests detected in maven-build.log." - fi - - - name: Upload Maven build log - if: always() - uses: actions/upload-artifact@v4 - with: - name: maven-build-log - if-no-files-found: ignore - path: | - maven-build.log - - - name: Upload test reports - if: always() - uses: actions/upload-artifact@v4 - with: - name: test-reports - if-no-files-found: ignore - path: | - obp-api/target/surefire-reports/** - obp-commons/target/surefire-reports/** - **/target/scalatest-reports/** - **/target/site/surefire-report.html - **/target/site/surefire-report/* - - - name: Save .war artifact - run: | - mkdir -p ./pull - cp obp-api/target/obp-api-1.*.war ./pull/ - - uses: actions/upload-artifact@v4 - with: - name: ${{ github.sha }} - path: pull/ - - - diff --git a/.github/workflows/run_trivy.yml b/.github/workflows/run_trivy.yml deleted file mode 100644 index 4636bd3116..0000000000 --- a/.github/workflows/run_trivy.yml +++ /dev/null @@ -1,54 +0,0 @@ -name: scan container image - -on: - workflow_run: - workflows: - - Build and publish container develop - - Build and publish container non develop - types: - - completed -env: - ## Sets environment variable - DOCKER_HUB_ORGANIZATION: ${{ vars.DOCKER_HUB_ORGANIZATION }} - DOCKER_HUB_REPOSITORY: obp-api - - -jobs: - build: - runs-on: ubuntu-latest - if: ${{ github.event.workflow_run.conclusion == 'success' }} - - steps: - - uses: actions/checkout@v4 - - id: trivy-db - name: Check trivy db sha - env: - GH_TOKEN: ${{ github.token }} - run: | - endpoint='/orgs/aquasecurity/packages/container/trivy-db/versions' - headers='Accept: application/vnd.github+json' - jqFilter='.[] | select(.metadata.container.tags[] | contains("latest")) | .name | sub("sha256:";"")' - sha=$(gh api -H "${headers}" "${endpoint}" | jq --raw-output "${jqFilter}") - echo "Trivy DB sha256:${sha}" - echo "::set-output name=sha::${sha}" - - uses: actions/cache@v4 - with: - path: .trivy - key: ${{ runner.os }}-trivy-db-${{ steps.trivy-db.outputs.sha }} - - name: Run Trivy vulnerability scanner - uses: aquasecurity/trivy-action@master - with: - image-ref: 'docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:${{ github.sha }}' - format: 'template' - template: '@/contrib/sarif.tpl' - output: 'trivy-results.sarif' - security-checks: 'vuln' - severity: 'CRITICAL,HIGH' - timeout: '30m' - cache-dir: .trivy - - name: Fix .trivy permissions - run: sudo chown -R $(stat . -c %u:%g) .trivy - - name: Upload Trivy scan results to GitHub Security tab - uses: github/codeql-action/upload-sarif@v3 - with: - sarif_file: 'trivy-results.sarif' \ No newline at end of file diff --git a/.gitignore b/.gitignore index 7e1e1bd937..1f8aabc66e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,3 @@ -.github/* *.class *.db .DS_Store From 2b4bda715777afda8e71a1394d95cfcb8b8593fa Mon Sep 17 00:00:00 2001 From: karmaking Date: Tue, 13 Jan 2026 14:46:31 +0100 Subject: [PATCH 2/8] edit gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 1f8aabc66e..7e1e1bd937 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ +.github/* *.class *.db .DS_Store From 3616788df211b45477821907675ecf9a5791a9d2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marko=20Mili=C4=87?= Date: Mon, 19 Jan 2026 17:10:28 +0100 Subject: [PATCH 3/8] feature/Remove Await.result from executeRule --- .../scala/code/abacrule/AbacRuleEngine.scala | 462 ++++++++++-------- .../src/main/scala/code/abacrule/README.md | 129 +++-- .../scala/code/api/v6_0_0/APIMethods600.scala | 58 +-- 3 files changed, 396 insertions(+), 253 deletions(-) diff --git a/obp-api/src/main/scala/code/abacrule/AbacRuleEngine.scala b/obp-api/src/main/scala/code/abacrule/AbacRuleEngine.scala index 93fb815371..057193ec5f 100644 --- a/obp-api/src/main/scala/code/abacrule/AbacRuleEngine.scala +++ b/obp-api/src/main/scala/code/abacrule/AbacRuleEngine.scala @@ -13,7 +13,7 @@ import net.liftweb.util.Helpers.tryo import java.util.concurrent.ConcurrentHashMap import scala.collection.JavaConverters._ import scala.collection.concurrent -import scala.concurrent.Await +import scala.concurrent.{Await, Future} import scala.concurrent.duration._ /** @@ -112,190 +112,221 @@ object AbacRuleEngine { transactionId: Option[String] = None, transactionRequestId: Option[String] = None, customerId: Option[String] = None + ): Future[Box[Boolean]] = { + val ruleBox = MappedAbacRuleProvider.getAbacRuleById(ruleId) + ruleBox match { + case Failure(msg, ex, chain) => Future.successful(Failure(msg, ex, chain)) + case Empty => Future.successful(Empty) + case Full(rule) => + if (!rule.isActive) { + Future.successful(Failure(s"ABAC Rule ${rule.ruleName} is not active")) + } else { + // Fetch authenticated user + val authenticatedUserBox = Users.users.vend.getUserByUserId(authenticatedUserId) + authenticatedUserBox match { + case Failure(msg, ex, chain) => Future.successful(Failure(msg, ex, chain)) + case Empty => Future.successful(Empty) + case Full(authenticatedUser) => + + // Create futures for all async operations + val authenticatedUserAttributesFuture = + code.api.util.NewStyle.function.getNonPersonalUserAttributes(authenticatedUserId, Some(callContext)).map(_._1) + + val authenticatedUserAuthContextFuture = + code.api.util.NewStyle.function.getUserAuthContexts(authenticatedUserId, Some(callContext)).map(_._1) + + val authenticatedUserEntitlementsFuture = + code.api.util.NewStyle.function.getEntitlementsByUserId(authenticatedUserId, Some(callContext)) + + val onBehalfOfUserFuture = onBehalfOfUserId match { + case Some(obUserId) => Future.successful(Users.users.vend.getUserByUserId(obUserId).map(Some(_))) + case None => Future.successful(Full(None)) + } + + val onBehalfOfUserAttributesFuture = onBehalfOfUserId match { + case Some(obUserId) => + code.api.util.NewStyle.function.getNonPersonalUserAttributes(obUserId, Some(callContext)).map(_._1) + case None => Future.successful(List.empty[UserAttributeTrait]) + } + + val onBehalfOfUserAuthContextFuture = onBehalfOfUserId match { + case Some(obUserId) => + code.api.util.NewStyle.function.getUserAuthContexts(obUserId, Some(callContext)).map(_._1) + case None => Future.successful(List.empty[UserAuthContext]) + } + + val onBehalfOfUserEntitlementsFuture = onBehalfOfUserId match { + case Some(obUserId) => + code.api.util.NewStyle.function.getEntitlementsByUserId(obUserId, Some(callContext)) + case None => Future.successful(List.empty[Entitlement]) + } + + val userFuture = userId match { + case Some(uId) => Future.successful(Users.users.vend.getUserByUserId(uId).map(Some(_))) + case None => Future.successful(Full(None)) + } + + val userAttributesFuture = userId match { + case Some(uId) => + code.api.util.NewStyle.function.getNonPersonalUserAttributes(uId, Some(callContext)).map(_._1) + case None => Future.successful(List.empty[UserAttributeTrait]) + } + + val bankFuture = bankId match { + case Some(bId) => + code.api.util.NewStyle.function.getBank(BankId(bId), Some(callContext)).map(_._1).map(bank => Full(Some(bank))).recover { + case _ => Full(None) + } + case None => Future.successful(Full(None)) + } + + val bankAttributesFuture = bankId match { + case Some(bId) => + code.api.util.NewStyle.function.getBankAttributesByBank(BankId(bId), Some(callContext)).map(_._1) + case None => Future.successful(List.empty[BankAttributeTrait]) + } + + val accountFuture = (bankId, accountId) match { + case (Some(bId), Some(aId)) => + code.api.util.NewStyle.function.getBankAccount(BankId(bId), AccountId(aId), Some(callContext)).map(_._1).map(account => Full(Some(account))).recover { + case _ => Full(None) + } + case _ => Future.successful(Full(None)) + } + + val accountAttributesFuture = (bankId, accountId) match { + case (Some(bId), Some(aId)) => + code.api.util.NewStyle.function.getAccountAttributesByAccount(BankId(bId), AccountId(aId), Some(callContext)).map(_._1) + case _ => Future.successful(List.empty[AccountAttribute]) + } + + val transactionFuture = (bankId, accountId, transactionId) match { + case (Some(bId), Some(aId), Some(tId)) => + code.api.util.NewStyle.function.getTransaction(BankId(bId), AccountId(aId), TransactionId(tId), Some(callContext)).map(_._1).map(trans => Full(Some(trans))).recover { + case _ => Full(None) + } + case _ => Future.successful(Full(None)) + } + + val transactionAttributesFuture = (bankId, transactionId) match { + case (Some(bId), Some(tId)) => + code.api.util.NewStyle.function.getTransactionAttributes(BankId(bId), TransactionId(tId), Some(callContext)).map(_._1) + case _ => Future.successful(List.empty[TransactionAttribute]) + } + + val transactionRequestFuture = transactionRequestId match { + case Some(trId) => + code.api.util.NewStyle.function.getTransactionRequestImpl(TransactionRequestId(trId), Some(callContext)).map(_._1).map(tr => Full(Some(tr))).recover { + case _ => Full(None) + } + case _ => Future.successful(Full(None)) + } + + val transactionRequestAttributesFuture = (bankId, transactionRequestId) match { + case (Some(bId), Some(trId)) => + code.api.util.NewStyle.function.getTransactionRequestAttributes(BankId(bId), TransactionRequestId(trId), Some(callContext)).map(_._1) + case _ => Future.successful(List.empty[TransactionRequestAttributeTrait]) + } + + val customerFuture = (bankId, customerId) match { + case (Some(bId), Some(cId)) => + code.api.util.NewStyle.function.getCustomerByCustomerId(cId, Some(callContext)).map(_._1).map(cust => Full(Some(cust))).recover { + case _ => Full(None) + } + case _ => Future.successful(Full(None)) + } + + val customerAttributesFuture = (bankId, customerId) match { + case (Some(bId), Some(cId)) => + code.api.util.NewStyle.function.getCustomerAttributes(BankId(bId), CustomerId(cId), Some(callContext)).map(_._1) + case _ => Future.successful(List.empty[CustomerAttribute]) + } + + // Combine all futures + for { + authenticatedUserAttributes <- authenticatedUserAttributesFuture + authenticatedUserAuthContext <- authenticatedUserAuthContextFuture + authenticatedUserEntitlements <- authenticatedUserEntitlementsFuture + onBehalfOfUserOpt <- onBehalfOfUserFuture + onBehalfOfUserAttributes <- onBehalfOfUserAttributesFuture + onBehalfOfUserAuthContext <- onBehalfOfUserAuthContextFuture + onBehalfOfUserEntitlements <- onBehalfOfUserEntitlementsFuture + userOpt <- userFuture + userAttributes <- userAttributesFuture + bankOpt <- bankFuture + bankAttributes <- bankAttributesFuture + accountOpt <- accountFuture + accountAttributes <- accountAttributesFuture + transactionOpt <- transactionFuture + transactionAttributes <- transactionAttributesFuture + transactionRequestOpt <- transactionRequestFuture + transactionRequestAttributes <- transactionRequestAttributesFuture + customerOpt <- customerFuture + customerAttributes <- customerAttributesFuture + } yield { + // Compile and execute the rule + val compiledFuncBox = compileRule(ruleId, rule.ruleCode) + compiledFuncBox.flatMap { compiledFunc => + (for { + onBehalfOfUser <- onBehalfOfUserOpt + user <- userOpt + bank <- bankOpt + account <- accountOpt + transaction <- transactionOpt + transactionRequest <- transactionRequestOpt + customer <- customerOpt + } yield { + tryo { + compiledFunc(authenticatedUser, authenticatedUserAttributes, authenticatedUserAuthContext, authenticatedUserEntitlements, onBehalfOfUser, onBehalfOfUserAttributes, onBehalfOfUserAuthContext, onBehalfOfUserEntitlements, user, userAttributes, bank, bankAttributes, account, accountAttributes, transaction, transactionAttributes, transactionRequest, transactionRequestAttributes, customer, customerAttributes, Some(callContext)) + } + }).flatten + } + } + } + } + } + } + + /** + * Synchronous wrapper for executeRule - DEPRECATED + * This function blocks the thread and should be avoided. Use the async version instead. + * + * @deprecated Use the async executeRule that returns Future[Box[Boolean]] instead + */ + @deprecated("Use async executeRule that returns Future[Box[Boolean]]", "6.0.0") + def executeRuleSync( + ruleId: String, + authenticatedUserId: String, + onBehalfOfUserId: Option[String] = None, + userId: Option[String] = None, + callContext: CallContext, + bankId: Option[String] = None, + accountId: Option[String] = None, + viewId: Option[String] = None, + transactionId: Option[String] = None, + transactionRequestId: Option[String] = None, + customerId: Option[String] = None ): Box[Boolean] = { - for { - rule <- MappedAbacRuleProvider.getAbacRuleById(ruleId) - _ <- if (rule.isActive) Full(true) else Failure(s"ABAC Rule ${rule.ruleName} is not active") - - // Fetch authenticated user (the actual person logged in) - authenticatedUser <- Users.users.vend.getUserByUserId(authenticatedUserId) - - // Fetch non-personal attributes for authenticated user - authenticatedUserAttributes = Await.result( - code.api.util.NewStyle.function.getNonPersonalUserAttributes(authenticatedUserId, Some(callContext)).map(_._1), - 5.seconds - ) - - // Fetch auth context for authenticated user - authenticatedUserAuthContext = Await.result( - code.api.util.NewStyle.function.getUserAuthContexts(authenticatedUserId, Some(callContext)).map(_._1), - 5.seconds - ) - - // Fetch entitlements for authenticated user - authenticatedUserEntitlements = Await.result( - code.api.util.NewStyle.function.getEntitlementsByUserId(authenticatedUserId, Some(callContext)), - 5.seconds - ) - - // Fetch onBehalfOf user if provided (delegation scenario) - onBehalfOfUserOpt <- onBehalfOfUserId match { - case Some(obUserId) => Users.users.vend.getUserByUserId(obUserId).map(Some(_)) - case None => Full(None) - } - - // Fetch attributes for onBehalfOf user if provided - onBehalfOfUserAttributes = onBehalfOfUserId match { - case Some(obUserId) => - Await.result( - code.api.util.NewStyle.function.getNonPersonalUserAttributes(obUserId, Some(callContext)).map(_._1), - 5.seconds - ) - case None => List.empty[UserAttributeTrait] - } - - // Fetch auth context for onBehalfOf user if provided - onBehalfOfUserAuthContext = onBehalfOfUserId match { - case Some(obUserId) => - Await.result( - code.api.util.NewStyle.function.getUserAuthContexts(obUserId, Some(callContext)).map(_._1), - 5.seconds - ) - case None => List.empty[UserAuthContext] - } - - // Fetch entitlements for onBehalfOf user if provided - onBehalfOfUserEntitlements = onBehalfOfUserId match { - case Some(obUserId) => - Await.result( - code.api.util.NewStyle.function.getEntitlementsByUserId(obUserId, Some(callContext)), - 5.seconds - ) - case None => List.empty[Entitlement] - } - - // Fetch target user if userId is provided - userOpt <- userId match { - case Some(uId) => Users.users.vend.getUserByUserId(uId).map(Some(_)) - case None => Full(None) - } - - // Fetch attributes for target user if provided - userAttributes = userId match { - case Some(uId) => - Await.result( - code.api.util.NewStyle.function.getNonPersonalUserAttributes(uId, Some(callContext)).map(_._1), - 5.seconds - ) - case None => List.empty[UserAttributeTrait] - } - - // Fetch bank if bankId is provided - bankOpt <- bankId match { - case Some(bId) => - tryo(Await.result( - code.api.util.NewStyle.function.getBank(BankId(bId), Some(callContext)).map(_._1), - 5.seconds - )).map(Some(_)) - case None => Full(None) - } - - // Fetch bank attributes if bank is provided - bankAttributes = bankId match { - case Some(bId) => - Await.result( - code.api.util.NewStyle.function.getBankAttributesByBank(BankId(bId), Some(callContext)).map(_._1), - 5.seconds - ) - case None => List.empty[BankAttributeTrait] - } - - // Fetch account if accountId and bankId are provided - accountOpt <- (bankId, accountId) match { - case (Some(bId), Some(aId)) => - tryo(Await.result( - code.api.util.NewStyle.function.getBankAccount(BankId(bId), AccountId(aId), Some(callContext)).map(_._1), - 5.seconds - )).map(Some(_)) - case _ => Full(None) - } - - // Fetch account attributes if account is provided - accountAttributes = (bankId, accountId) match { - case (Some(bId), Some(aId)) => - Await.result( - code.api.util.NewStyle.function.getAccountAttributesByAccount(BankId(bId), AccountId(aId), Some(callContext)).map(_._1), - 5.seconds - ) - case _ => List.empty[AccountAttribute] - } - - // Fetch transaction if transactionId, accountId, and bankId are provided - transactionOpt <- (bankId, accountId, transactionId) match { - case (Some(bId), Some(aId), Some(tId)) => - tryo(Await.result( - code.api.util.NewStyle.function.getTransaction(BankId(bId), AccountId(aId), TransactionId(tId), Some(callContext)).map(_._1), - 5.seconds - )).map(trans => Some(trans)) - case _ => Full(None) - } - - // Fetch transaction attributes if transaction is provided - transactionAttributes = (bankId, transactionId) match { - case (Some(bId), Some(tId)) => - Await.result( - code.api.util.NewStyle.function.getTransactionAttributes(BankId(bId), TransactionId(tId), Some(callContext)).map(_._1), - 5.seconds - ) - case _ => List.empty[TransactionAttribute] - } - - // Fetch transaction request if transactionRequestId is provided - transactionRequestOpt <- transactionRequestId match { - case Some(trId) => - tryo(Await.result( - code.api.util.NewStyle.function.getTransactionRequestImpl(TransactionRequestId(trId), Some(callContext)).map(_._1), - 5.seconds - )).map(tr => Some(tr)) - case _ => Full(None) - } - - // Fetch transaction request attributes if transaction request is provided - transactionRequestAttributes = (bankId, transactionRequestId) match { - case (Some(bId), Some(trId)) => - Await.result( - code.api.util.NewStyle.function.getTransactionRequestAttributes(BankId(bId), TransactionRequestId(trId), Some(callContext)).map(_._1), - 5.seconds - ) - case _ => List.empty[TransactionRequestAttributeTrait] - } - - // Fetch customer if customerId and bankId are provided - customerOpt <- (bankId, customerId) match { - case (Some(bId), Some(cId)) => - tryo(Await.result( - code.api.util.NewStyle.function.getCustomerByCustomerId(cId, Some(callContext)).map(_._1), - 5.seconds - )).map(cust => Some(cust)) - case _ => Full(None) - } - - // Fetch customer attributes if customer is provided - customerAttributes = (bankId, customerId) match { - case (Some(bId), Some(cId)) => - Await.result( - code.api.util.NewStyle.function.getCustomerAttributes(BankId(bId), CustomerId(cId), Some(callContext)).map(_._1), - 5.seconds - ) - case _ => List.empty[CustomerAttribute] - } - - // Compile and execute the rule - compiledFunc <- compileRule(ruleId, rule.ruleCode) - result <- tryo { - compiledFunc(authenticatedUser, authenticatedUserAttributes, authenticatedUserAuthContext, authenticatedUserEntitlements, onBehalfOfUserOpt, onBehalfOfUserAttributes, onBehalfOfUserAuthContext, onBehalfOfUserEntitlements, userOpt, userAttributes, bankOpt, bankAttributes, accountOpt, accountAttributes, transactionOpt, transactionAttributes, transactionRequestOpt, transactionRequestAttributes, customerOpt, customerAttributes, Some(callContext)) - } - } yield result + try { + Await.result(executeRule( + ruleId = ruleId, + authenticatedUserId = authenticatedUserId, + onBehalfOfUserId = onBehalfOfUserId, + userId = userId, + callContext = callContext, + bankId = bankId, + accountId = accountId, + viewId = viewId, + transactionId = transactionId, + transactionRequestId = transactionRequestId, + customerId = customerId + ), 30.seconds) + } catch { + case _: java.util.concurrent.TimeoutException => + Failure("ABAC rule execution timed out") + case ex: Exception => + Failure(s"ABAC rule execution failed: ${ex.getMessage}") + } } @@ -329,15 +360,15 @@ object AbacRuleEngine { transactionId: Option[String] = None, transactionRequestId: Option[String] = None, customerId: Option[String] = None - ): Box[Boolean] = { + ): Future[Box[Boolean]] = { val rules = MappedAbacRuleProvider.getActiveAbacRulesByPolicy(policy) if (rules.isEmpty) { // No rules for this policy - default to allow - Full(true) + Future.successful(Full(true)) } else { // Execute all rules and check if at least one passes - val results = rules.map { rule => + val ruleFutures = rules.map { rule => executeRule( ruleId = rule.abacRuleId, authenticatedUserId = authenticatedUserId, @@ -353,14 +384,59 @@ object AbacRuleEngine { ) } - // Count successes and failures - val successes = results.filter { - case Full(true) => true - case _ => false + // Wait for all rule executions to complete + Future.sequence(ruleFutures).map { results => + // Count successes and failures + val successes = results.filter { + case Full(true) => true + case _ => false + } + + // At least one rule must pass (OR logic) + Full(successes.nonEmpty) } + } + } - // At least one rule must pass (OR logic) - Full(successes.nonEmpty) + /** + * Synchronous wrapper for executeRulesByPolicy - DEPRECATED + * This function blocks the thread and should be avoided. Use the async version instead. + * + * @deprecated Use async executeRulesByPolicy that returns Future[Box[Boolean]] instead + */ + @deprecated("Use async executeRulesByPolicy that returns Future[Box[Boolean]]", "6.0.0") + def executeRulesByPolicySync( + policy: String, + authenticatedUserId: String, + onBehalfOfUserId: Option[String] = None, + userId: Option[String] = None, + callContext: CallContext, + bankId: Option[String] = None, + accountId: Option[String] = None, + viewId: Option[String] = None, + transactionId: Option[String] = None, + transactionRequestId: Option[String] = None, + customerId: Option[String] = None + ): Box[Boolean] = { + try { + Await.result(executeRulesByPolicy( + policy = policy, + authenticatedUserId = authenticatedUserId, + onBehalfOfUserId = onBehalfOfUserId, + userId = userId, + callContext = callContext, + bankId = bankId, + accountId = accountId, + viewId = viewId, + transactionId = transactionId, + transactionRequestId = transactionRequestId, + customerId = customerId + ), 30.seconds) + } catch { + case _: java.util.concurrent.TimeoutException => + Failure("ABAC rules execution timed out") + case ex: Exception => + Failure(s"ABAC rules execution failed: ${ex.getMessage}") } } diff --git a/obp-api/src/main/scala/code/abacrule/README.md b/obp-api/src/main/scala/code/abacrule/README.md index f845490bea..c428594985 100644 --- a/obp-api/src/main/scala/code/abacrule/README.md +++ b/obp-api/src/main/scala/code/abacrule/README.md @@ -177,18 +177,54 @@ val ruleCode = """user.emailAddress.contains("admin")""" val compiled = AbacRuleEngine.compileRule("rule123", ruleCode) ``` -### Execute a Rule +### Execute a Rule (Async - Recommended) ```scala import code.abacrule.AbacRuleEngine import com.openbankproject.commons.model._ +import scala.concurrent.Future -val result = AbacRuleEngine.executeRule( +val resultFuture: Future[Box[Boolean]] = AbacRuleEngine.executeRule( ruleId = "rule123", - user = currentUser, - bankOpt = Some(bank), - accountOpt = Some(account), - transactionOpt = None, - customerOpt = None + authenticatedUserId = currentUser.userId, + onBehalfOfUserId = None, + userId = Some(targetUser.userId), + callContext = callContext, + bankId = Some(bank.bankId.value), + accountId = Some(account.accountId.value), + viewId = None, + transactionId = None, + transactionRequestId = None, + customerId = None +) + +resultFuture.map { result => + result match { + case Full(true) => println("Access granted") + case Full(false) => println("Access denied") + case Failure(msg, _, _) => println(s"Error: $msg") + case Empty => println("Rule not found") + } +} +``` + +### Execute a Rule (Sync - Deprecated) +```scala +import code.abacrule.AbacRuleEngine +import com.openbankproject.commons.model._ + +// This is deprecated and blocks the thread - use async version above instead +val result = AbacRuleEngine.executeRuleSync( + ruleId = "rule123", + authenticatedUserId = currentUser.userId, + onBehalfOfUserId = None, + userId = Some(targetUser.userId), + callContext = callContext, + bankId = Some(bank.bankId.value), + accountId = Some(account.accountId.value), + viewId = None, + transactionId = None, + transactionRequestId = None, + customerId = None ) result match { @@ -199,24 +235,56 @@ result match { } ``` -### Execute Multiple Rules (AND Logic) -All rules must pass: +### Execute Rules by Policy (Async - Recommended) +Execute all active rules associated with a policy (OR logic - at least one must pass): ```scala -val result = AbacRuleEngine.executeRulesAnd( - ruleIds = List("rule1", "rule2", "rule3"), - user = currentUser, - bankOpt = Some(bank) +val resultFuture: Future[Box[Boolean]] = AbacRuleEngine.executeRulesByPolicy( + policy = "account_access_policy", + authenticatedUserId = currentUser.userId, + onBehalfOfUserId = None, + userId = Some(targetUser.userId), + callContext = callContext, + bankId = Some(bank.bankId.value), + accountId = Some(account.accountId.value), + viewId = None, + transactionId = None, + transactionRequestId = None, + customerId = None ) + +resultFuture.map { result => + result match { + case Full(true) => println("Access granted by policy") + case Full(false) => println("Access denied by policy") + case Failure(msg, _, _) => println(s"Error: $msg") + case Empty => println("Policy not found") + } +} ``` -### Execute Multiple Rules (OR Logic) -At least one rule must pass: +### Execute Rules by Policy (Sync - Deprecated) ```scala -val result = AbacRuleEngine.executeRulesOr( - ruleIds = List("rule1", "rule2", "rule3"), - user = currentUser, - bankOpt = Some(bank) +// This is deprecated and blocks the thread - use async version above instead +val result = AbacRuleEngine.executeRulesByPolicySync( + policy = "account_access_policy", + authenticatedUserId = currentUser.userId, + onBehalfOfUserId = None, + userId = Some(targetUser.userId), + callContext = callContext, + bankId = Some(bank.bankId.value), + accountId = Some(account.accountId.value), + viewId = None, + transactionId = None, + transactionRequestId = None, + customerId = None ) + +result match { + case Full(true) => println("Access granted by policy") + case Full(false) => println("Access denied by policy") + case Failure(msg, _, _) => println(s"Error: $msg") + case Empty => println("Policy not found") +} ``` ### Validate Rule Code @@ -341,16 +409,19 @@ for { (account, callContext) <- NewStyle.function.getBankAccount(bankId, accountId, callContext) // Check ABAC rules - allowed <- Future { - AbacRuleEngine.executeRulesAnd( - ruleIds = List("bank_access_rule", "account_limit_rule"), - user = user, - bankOpt = Some(bank), - accountOpt = Some(account) - ) - } map { - unboxFullOrFail(_, callContext, "ABAC access check failed", 403) - } + allowed <- AbacRuleEngine.executeRulesByPolicy( + policy = "bank_access_policy", + authenticatedUserId = user.userId, + onBehalfOfUserId = None, + userId = Some(user.userId), + callContext = callContext, + bankId = Some(bank.bankId.value), + accountId = Some(account.accountId.value), + viewId = None, + transactionId = None, + transactionRequestId = None, + customerId = None + ) _ <- Helper.booleanToFuture(s"Access denied by ABAC rules", cc = callContext) { allowed diff --git a/obp-api/src/main/scala/code/api/v6_0_0/APIMethods600.scala b/obp-api/src/main/scala/code/api/v6_0_0/APIMethods600.scala index 6331f2a442..919bddcc84 100644 --- a/obp-api/src/main/scala/code/api/v6_0_0/APIMethods600.scala +++ b/obp-api/src/main/scala/code/api/v6_0_0/APIMethods600.scala @@ -5610,7 +5610,7 @@ trait APIMethods600 { result = true ), List( - UserNotLoggedIn, + $UserNotLoggedIn, UserHasMissingRoles, InvalidJsonFormat, UnknownError @@ -5640,21 +5640,19 @@ trait APIMethods600 { // userId: the target user being evaluated (defaults to authenticated user) effectiveAuthenticatedUserId = execJson.authenticated_user_id.getOrElse(user.userId) - result <- Future { - val resultBox = AbacRuleEngine.executeRule( - ruleId = ruleId, - authenticatedUserId = effectiveAuthenticatedUserId, - onBehalfOfUserId = execJson.on_behalf_of_user_id, - userId = execJson.user_id, - callContext = callContext.getOrElse(cc), - bankId = execJson.bank_id, - accountId = execJson.account_id, - viewId = execJson.view_id, - transactionId = execJson.transaction_id, - transactionRequestId = execJson.transaction_request_id, - customerId = execJson.customer_id - ) - + result <- AbacRuleEngine.executeRule( + ruleId = ruleId, + authenticatedUserId = effectiveAuthenticatedUserId, + onBehalfOfUserId = execJson.on_behalf_of_user_id, + userId = execJson.user_id, + callContext = callContext.getOrElse(cc), + bankId = execJson.bank_id, + accountId = execJson.account_id, + viewId = execJson.view_id, + transactionId = execJson.transaction_id, + transactionRequestId = execJson.transaction_request_id, + customerId = execJson.customer_id + ).map { resultBox => resultBox match { case Full(allowed) => AbacRuleResultJsonV600(result = allowed) @@ -5746,21 +5744,19 @@ trait APIMethods600 { // userId: the target user being evaluated (defaults to authenticated user) effectiveAuthenticatedUserId = execJson.authenticated_user_id.getOrElse(user.userId) - result <- Future { - val resultBox = AbacRuleEngine.executeRulesByPolicy( - policy = policy, - authenticatedUserId = effectiveAuthenticatedUserId, - onBehalfOfUserId = execJson.on_behalf_of_user_id, - userId = execJson.user_id, - callContext = callContext.getOrElse(cc), - bankId = execJson.bank_id, - accountId = execJson.account_id, - viewId = execJson.view_id, - transactionId = execJson.transaction_id, - transactionRequestId = execJson.transaction_request_id, - customerId = execJson.customer_id - ) - + result <- AbacRuleEngine.executeRulesByPolicy( + policy = policy, + authenticatedUserId = effectiveAuthenticatedUserId, + onBehalfOfUserId = execJson.on_behalf_of_user_id, + userId = execJson.user_id, + callContext = callContext.getOrElse(cc), + bankId = execJson.bank_id, + accountId = execJson.account_id, + viewId = execJson.view_id, + transactionId = execJson.transaction_id, + transactionRequestId = execJson.transaction_request_id, + customerId = execJson.customer_id + ).map { resultBox => resultBox match { case Full(allowed) => AbacRuleResultJsonV600(result = allowed) From 79ea9231a19ab723f732413beb3a7f5d61f6aab3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marko=20Mili=C4=87?= Date: Fri, 23 Jan 2026 12:41:26 +0100 Subject: [PATCH 4/8] Merge upstream/develop into develop after conflict resolution --- .../scala/code/abacrule/AbacRuleEngine.scala | 462 ++++++++---------- .../src/main/scala/code/abacrule/README.md | 129 ++--- 2 files changed, 222 insertions(+), 369 deletions(-) diff --git a/obp-api/src/main/scala/code/abacrule/AbacRuleEngine.scala b/obp-api/src/main/scala/code/abacrule/AbacRuleEngine.scala index 057193ec5f..93fb815371 100644 --- a/obp-api/src/main/scala/code/abacrule/AbacRuleEngine.scala +++ b/obp-api/src/main/scala/code/abacrule/AbacRuleEngine.scala @@ -13,7 +13,7 @@ import net.liftweb.util.Helpers.tryo import java.util.concurrent.ConcurrentHashMap import scala.collection.JavaConverters._ import scala.collection.concurrent -import scala.concurrent.{Await, Future} +import scala.concurrent.Await import scala.concurrent.duration._ /** @@ -112,221 +112,190 @@ object AbacRuleEngine { transactionId: Option[String] = None, transactionRequestId: Option[String] = None, customerId: Option[String] = None - ): Future[Box[Boolean]] = { - val ruleBox = MappedAbacRuleProvider.getAbacRuleById(ruleId) - ruleBox match { - case Failure(msg, ex, chain) => Future.successful(Failure(msg, ex, chain)) - case Empty => Future.successful(Empty) - case Full(rule) => - if (!rule.isActive) { - Future.successful(Failure(s"ABAC Rule ${rule.ruleName} is not active")) - } else { - // Fetch authenticated user - val authenticatedUserBox = Users.users.vend.getUserByUserId(authenticatedUserId) - authenticatedUserBox match { - case Failure(msg, ex, chain) => Future.successful(Failure(msg, ex, chain)) - case Empty => Future.successful(Empty) - case Full(authenticatedUser) => - - // Create futures for all async operations - val authenticatedUserAttributesFuture = - code.api.util.NewStyle.function.getNonPersonalUserAttributes(authenticatedUserId, Some(callContext)).map(_._1) - - val authenticatedUserAuthContextFuture = - code.api.util.NewStyle.function.getUserAuthContexts(authenticatedUserId, Some(callContext)).map(_._1) - - val authenticatedUserEntitlementsFuture = - code.api.util.NewStyle.function.getEntitlementsByUserId(authenticatedUserId, Some(callContext)) - - val onBehalfOfUserFuture = onBehalfOfUserId match { - case Some(obUserId) => Future.successful(Users.users.vend.getUserByUserId(obUserId).map(Some(_))) - case None => Future.successful(Full(None)) - } - - val onBehalfOfUserAttributesFuture = onBehalfOfUserId match { - case Some(obUserId) => - code.api.util.NewStyle.function.getNonPersonalUserAttributes(obUserId, Some(callContext)).map(_._1) - case None => Future.successful(List.empty[UserAttributeTrait]) - } - - val onBehalfOfUserAuthContextFuture = onBehalfOfUserId match { - case Some(obUserId) => - code.api.util.NewStyle.function.getUserAuthContexts(obUserId, Some(callContext)).map(_._1) - case None => Future.successful(List.empty[UserAuthContext]) - } - - val onBehalfOfUserEntitlementsFuture = onBehalfOfUserId match { - case Some(obUserId) => - code.api.util.NewStyle.function.getEntitlementsByUserId(obUserId, Some(callContext)) - case None => Future.successful(List.empty[Entitlement]) - } - - val userFuture = userId match { - case Some(uId) => Future.successful(Users.users.vend.getUserByUserId(uId).map(Some(_))) - case None => Future.successful(Full(None)) - } - - val userAttributesFuture = userId match { - case Some(uId) => - code.api.util.NewStyle.function.getNonPersonalUserAttributes(uId, Some(callContext)).map(_._1) - case None => Future.successful(List.empty[UserAttributeTrait]) - } - - val bankFuture = bankId match { - case Some(bId) => - code.api.util.NewStyle.function.getBank(BankId(bId), Some(callContext)).map(_._1).map(bank => Full(Some(bank))).recover { - case _ => Full(None) - } - case None => Future.successful(Full(None)) - } - - val bankAttributesFuture = bankId match { - case Some(bId) => - code.api.util.NewStyle.function.getBankAttributesByBank(BankId(bId), Some(callContext)).map(_._1) - case None => Future.successful(List.empty[BankAttributeTrait]) - } - - val accountFuture = (bankId, accountId) match { - case (Some(bId), Some(aId)) => - code.api.util.NewStyle.function.getBankAccount(BankId(bId), AccountId(aId), Some(callContext)).map(_._1).map(account => Full(Some(account))).recover { - case _ => Full(None) - } - case _ => Future.successful(Full(None)) - } - - val accountAttributesFuture = (bankId, accountId) match { - case (Some(bId), Some(aId)) => - code.api.util.NewStyle.function.getAccountAttributesByAccount(BankId(bId), AccountId(aId), Some(callContext)).map(_._1) - case _ => Future.successful(List.empty[AccountAttribute]) - } - - val transactionFuture = (bankId, accountId, transactionId) match { - case (Some(bId), Some(aId), Some(tId)) => - code.api.util.NewStyle.function.getTransaction(BankId(bId), AccountId(aId), TransactionId(tId), Some(callContext)).map(_._1).map(trans => Full(Some(trans))).recover { - case _ => Full(None) - } - case _ => Future.successful(Full(None)) - } - - val transactionAttributesFuture = (bankId, transactionId) match { - case (Some(bId), Some(tId)) => - code.api.util.NewStyle.function.getTransactionAttributes(BankId(bId), TransactionId(tId), Some(callContext)).map(_._1) - case _ => Future.successful(List.empty[TransactionAttribute]) - } - - val transactionRequestFuture = transactionRequestId match { - case Some(trId) => - code.api.util.NewStyle.function.getTransactionRequestImpl(TransactionRequestId(trId), Some(callContext)).map(_._1).map(tr => Full(Some(tr))).recover { - case _ => Full(None) - } - case _ => Future.successful(Full(None)) - } - - val transactionRequestAttributesFuture = (bankId, transactionRequestId) match { - case (Some(bId), Some(trId)) => - code.api.util.NewStyle.function.getTransactionRequestAttributes(BankId(bId), TransactionRequestId(trId), Some(callContext)).map(_._1) - case _ => Future.successful(List.empty[TransactionRequestAttributeTrait]) - } - - val customerFuture = (bankId, customerId) match { - case (Some(bId), Some(cId)) => - code.api.util.NewStyle.function.getCustomerByCustomerId(cId, Some(callContext)).map(_._1).map(cust => Full(Some(cust))).recover { - case _ => Full(None) - } - case _ => Future.successful(Full(None)) - } - - val customerAttributesFuture = (bankId, customerId) match { - case (Some(bId), Some(cId)) => - code.api.util.NewStyle.function.getCustomerAttributes(BankId(bId), CustomerId(cId), Some(callContext)).map(_._1) - case _ => Future.successful(List.empty[CustomerAttribute]) - } - - // Combine all futures - for { - authenticatedUserAttributes <- authenticatedUserAttributesFuture - authenticatedUserAuthContext <- authenticatedUserAuthContextFuture - authenticatedUserEntitlements <- authenticatedUserEntitlementsFuture - onBehalfOfUserOpt <- onBehalfOfUserFuture - onBehalfOfUserAttributes <- onBehalfOfUserAttributesFuture - onBehalfOfUserAuthContext <- onBehalfOfUserAuthContextFuture - onBehalfOfUserEntitlements <- onBehalfOfUserEntitlementsFuture - userOpt <- userFuture - userAttributes <- userAttributesFuture - bankOpt <- bankFuture - bankAttributes <- bankAttributesFuture - accountOpt <- accountFuture - accountAttributes <- accountAttributesFuture - transactionOpt <- transactionFuture - transactionAttributes <- transactionAttributesFuture - transactionRequestOpt <- transactionRequestFuture - transactionRequestAttributes <- transactionRequestAttributesFuture - customerOpt <- customerFuture - customerAttributes <- customerAttributesFuture - } yield { - // Compile and execute the rule - val compiledFuncBox = compileRule(ruleId, rule.ruleCode) - compiledFuncBox.flatMap { compiledFunc => - (for { - onBehalfOfUser <- onBehalfOfUserOpt - user <- userOpt - bank <- bankOpt - account <- accountOpt - transaction <- transactionOpt - transactionRequest <- transactionRequestOpt - customer <- customerOpt - } yield { - tryo { - compiledFunc(authenticatedUser, authenticatedUserAttributes, authenticatedUserAuthContext, authenticatedUserEntitlements, onBehalfOfUser, onBehalfOfUserAttributes, onBehalfOfUserAuthContext, onBehalfOfUserEntitlements, user, userAttributes, bank, bankAttributes, account, accountAttributes, transaction, transactionAttributes, transactionRequest, transactionRequestAttributes, customer, customerAttributes, Some(callContext)) - } - }).flatten - } - } - } - } - } - } - - /** - * Synchronous wrapper for executeRule - DEPRECATED - * This function blocks the thread and should be avoided. Use the async version instead. - * - * @deprecated Use the async executeRule that returns Future[Box[Boolean]] instead - */ - @deprecated("Use async executeRule that returns Future[Box[Boolean]]", "6.0.0") - def executeRuleSync( - ruleId: String, - authenticatedUserId: String, - onBehalfOfUserId: Option[String] = None, - userId: Option[String] = None, - callContext: CallContext, - bankId: Option[String] = None, - accountId: Option[String] = None, - viewId: Option[String] = None, - transactionId: Option[String] = None, - transactionRequestId: Option[String] = None, - customerId: Option[String] = None ): Box[Boolean] = { - try { - Await.result(executeRule( - ruleId = ruleId, - authenticatedUserId = authenticatedUserId, - onBehalfOfUserId = onBehalfOfUserId, - userId = userId, - callContext = callContext, - bankId = bankId, - accountId = accountId, - viewId = viewId, - transactionId = transactionId, - transactionRequestId = transactionRequestId, - customerId = customerId - ), 30.seconds) - } catch { - case _: java.util.concurrent.TimeoutException => - Failure("ABAC rule execution timed out") - case ex: Exception => - Failure(s"ABAC rule execution failed: ${ex.getMessage}") - } + for { + rule <- MappedAbacRuleProvider.getAbacRuleById(ruleId) + _ <- if (rule.isActive) Full(true) else Failure(s"ABAC Rule ${rule.ruleName} is not active") + + // Fetch authenticated user (the actual person logged in) + authenticatedUser <- Users.users.vend.getUserByUserId(authenticatedUserId) + + // Fetch non-personal attributes for authenticated user + authenticatedUserAttributes = Await.result( + code.api.util.NewStyle.function.getNonPersonalUserAttributes(authenticatedUserId, Some(callContext)).map(_._1), + 5.seconds + ) + + // Fetch auth context for authenticated user + authenticatedUserAuthContext = Await.result( + code.api.util.NewStyle.function.getUserAuthContexts(authenticatedUserId, Some(callContext)).map(_._1), + 5.seconds + ) + + // Fetch entitlements for authenticated user + authenticatedUserEntitlements = Await.result( + code.api.util.NewStyle.function.getEntitlementsByUserId(authenticatedUserId, Some(callContext)), + 5.seconds + ) + + // Fetch onBehalfOf user if provided (delegation scenario) + onBehalfOfUserOpt <- onBehalfOfUserId match { + case Some(obUserId) => Users.users.vend.getUserByUserId(obUserId).map(Some(_)) + case None => Full(None) + } + + // Fetch attributes for onBehalfOf user if provided + onBehalfOfUserAttributes = onBehalfOfUserId match { + case Some(obUserId) => + Await.result( + code.api.util.NewStyle.function.getNonPersonalUserAttributes(obUserId, Some(callContext)).map(_._1), + 5.seconds + ) + case None => List.empty[UserAttributeTrait] + } + + // Fetch auth context for onBehalfOf user if provided + onBehalfOfUserAuthContext = onBehalfOfUserId match { + case Some(obUserId) => + Await.result( + code.api.util.NewStyle.function.getUserAuthContexts(obUserId, Some(callContext)).map(_._1), + 5.seconds + ) + case None => List.empty[UserAuthContext] + } + + // Fetch entitlements for onBehalfOf user if provided + onBehalfOfUserEntitlements = onBehalfOfUserId match { + case Some(obUserId) => + Await.result( + code.api.util.NewStyle.function.getEntitlementsByUserId(obUserId, Some(callContext)), + 5.seconds + ) + case None => List.empty[Entitlement] + } + + // Fetch target user if userId is provided + userOpt <- userId match { + case Some(uId) => Users.users.vend.getUserByUserId(uId).map(Some(_)) + case None => Full(None) + } + + // Fetch attributes for target user if provided + userAttributes = userId match { + case Some(uId) => + Await.result( + code.api.util.NewStyle.function.getNonPersonalUserAttributes(uId, Some(callContext)).map(_._1), + 5.seconds + ) + case None => List.empty[UserAttributeTrait] + } + + // Fetch bank if bankId is provided + bankOpt <- bankId match { + case Some(bId) => + tryo(Await.result( + code.api.util.NewStyle.function.getBank(BankId(bId), Some(callContext)).map(_._1), + 5.seconds + )).map(Some(_)) + case None => Full(None) + } + + // Fetch bank attributes if bank is provided + bankAttributes = bankId match { + case Some(bId) => + Await.result( + code.api.util.NewStyle.function.getBankAttributesByBank(BankId(bId), Some(callContext)).map(_._1), + 5.seconds + ) + case None => List.empty[BankAttributeTrait] + } + + // Fetch account if accountId and bankId are provided + accountOpt <- (bankId, accountId) match { + case (Some(bId), Some(aId)) => + tryo(Await.result( + code.api.util.NewStyle.function.getBankAccount(BankId(bId), AccountId(aId), Some(callContext)).map(_._1), + 5.seconds + )).map(Some(_)) + case _ => Full(None) + } + + // Fetch account attributes if account is provided + accountAttributes = (bankId, accountId) match { + case (Some(bId), Some(aId)) => + Await.result( + code.api.util.NewStyle.function.getAccountAttributesByAccount(BankId(bId), AccountId(aId), Some(callContext)).map(_._1), + 5.seconds + ) + case _ => List.empty[AccountAttribute] + } + + // Fetch transaction if transactionId, accountId, and bankId are provided + transactionOpt <- (bankId, accountId, transactionId) match { + case (Some(bId), Some(aId), Some(tId)) => + tryo(Await.result( + code.api.util.NewStyle.function.getTransaction(BankId(bId), AccountId(aId), TransactionId(tId), Some(callContext)).map(_._1), + 5.seconds + )).map(trans => Some(trans)) + case _ => Full(None) + } + + // Fetch transaction attributes if transaction is provided + transactionAttributes = (bankId, transactionId) match { + case (Some(bId), Some(tId)) => + Await.result( + code.api.util.NewStyle.function.getTransactionAttributes(BankId(bId), TransactionId(tId), Some(callContext)).map(_._1), + 5.seconds + ) + case _ => List.empty[TransactionAttribute] + } + + // Fetch transaction request if transactionRequestId is provided + transactionRequestOpt <- transactionRequestId match { + case Some(trId) => + tryo(Await.result( + code.api.util.NewStyle.function.getTransactionRequestImpl(TransactionRequestId(trId), Some(callContext)).map(_._1), + 5.seconds + )).map(tr => Some(tr)) + case _ => Full(None) + } + + // Fetch transaction request attributes if transaction request is provided + transactionRequestAttributes = (bankId, transactionRequestId) match { + case (Some(bId), Some(trId)) => + Await.result( + code.api.util.NewStyle.function.getTransactionRequestAttributes(BankId(bId), TransactionRequestId(trId), Some(callContext)).map(_._1), + 5.seconds + ) + case _ => List.empty[TransactionRequestAttributeTrait] + } + + // Fetch customer if customerId and bankId are provided + customerOpt <- (bankId, customerId) match { + case (Some(bId), Some(cId)) => + tryo(Await.result( + code.api.util.NewStyle.function.getCustomerByCustomerId(cId, Some(callContext)).map(_._1), + 5.seconds + )).map(cust => Some(cust)) + case _ => Full(None) + } + + // Fetch customer attributes if customer is provided + customerAttributes = (bankId, customerId) match { + case (Some(bId), Some(cId)) => + Await.result( + code.api.util.NewStyle.function.getCustomerAttributes(BankId(bId), CustomerId(cId), Some(callContext)).map(_._1), + 5.seconds + ) + case _ => List.empty[CustomerAttribute] + } + + // Compile and execute the rule + compiledFunc <- compileRule(ruleId, rule.ruleCode) + result <- tryo { + compiledFunc(authenticatedUser, authenticatedUserAttributes, authenticatedUserAuthContext, authenticatedUserEntitlements, onBehalfOfUserOpt, onBehalfOfUserAttributes, onBehalfOfUserAuthContext, onBehalfOfUserEntitlements, userOpt, userAttributes, bankOpt, bankAttributes, accountOpt, accountAttributes, transactionOpt, transactionAttributes, transactionRequestOpt, transactionRequestAttributes, customerOpt, customerAttributes, Some(callContext)) + } + } yield result } @@ -360,15 +329,15 @@ object AbacRuleEngine { transactionId: Option[String] = None, transactionRequestId: Option[String] = None, customerId: Option[String] = None - ): Future[Box[Boolean]] = { + ): Box[Boolean] = { val rules = MappedAbacRuleProvider.getActiveAbacRulesByPolicy(policy) if (rules.isEmpty) { // No rules for this policy - default to allow - Future.successful(Full(true)) + Full(true) } else { // Execute all rules and check if at least one passes - val ruleFutures = rules.map { rule => + val results = rules.map { rule => executeRule( ruleId = rule.abacRuleId, authenticatedUserId = authenticatedUserId, @@ -384,59 +353,14 @@ object AbacRuleEngine { ) } - // Wait for all rule executions to complete - Future.sequence(ruleFutures).map { results => - // Count successes and failures - val successes = results.filter { - case Full(true) => true - case _ => false - } - - // At least one rule must pass (OR logic) - Full(successes.nonEmpty) + // Count successes and failures + val successes = results.filter { + case Full(true) => true + case _ => false } - } - } - /** - * Synchronous wrapper for executeRulesByPolicy - DEPRECATED - * This function blocks the thread and should be avoided. Use the async version instead. - * - * @deprecated Use async executeRulesByPolicy that returns Future[Box[Boolean]] instead - */ - @deprecated("Use async executeRulesByPolicy that returns Future[Box[Boolean]]", "6.0.0") - def executeRulesByPolicySync( - policy: String, - authenticatedUserId: String, - onBehalfOfUserId: Option[String] = None, - userId: Option[String] = None, - callContext: CallContext, - bankId: Option[String] = None, - accountId: Option[String] = None, - viewId: Option[String] = None, - transactionId: Option[String] = None, - transactionRequestId: Option[String] = None, - customerId: Option[String] = None - ): Box[Boolean] = { - try { - Await.result(executeRulesByPolicy( - policy = policy, - authenticatedUserId = authenticatedUserId, - onBehalfOfUserId = onBehalfOfUserId, - userId = userId, - callContext = callContext, - bankId = bankId, - accountId = accountId, - viewId = viewId, - transactionId = transactionId, - transactionRequestId = transactionRequestId, - customerId = customerId - ), 30.seconds) - } catch { - case _: java.util.concurrent.TimeoutException => - Failure("ABAC rules execution timed out") - case ex: Exception => - Failure(s"ABAC rules execution failed: ${ex.getMessage}") + // At least one rule must pass (OR logic) + Full(successes.nonEmpty) } } diff --git a/obp-api/src/main/scala/code/abacrule/README.md b/obp-api/src/main/scala/code/abacrule/README.md index c428594985..f845490bea 100644 --- a/obp-api/src/main/scala/code/abacrule/README.md +++ b/obp-api/src/main/scala/code/abacrule/README.md @@ -177,54 +177,18 @@ val ruleCode = """user.emailAddress.contains("admin")""" val compiled = AbacRuleEngine.compileRule("rule123", ruleCode) ``` -### Execute a Rule (Async - Recommended) +### Execute a Rule ```scala import code.abacrule.AbacRuleEngine import com.openbankproject.commons.model._ -import scala.concurrent.Future -val resultFuture: Future[Box[Boolean]] = AbacRuleEngine.executeRule( +val result = AbacRuleEngine.executeRule( ruleId = "rule123", - authenticatedUserId = currentUser.userId, - onBehalfOfUserId = None, - userId = Some(targetUser.userId), - callContext = callContext, - bankId = Some(bank.bankId.value), - accountId = Some(account.accountId.value), - viewId = None, - transactionId = None, - transactionRequestId = None, - customerId = None -) - -resultFuture.map { result => - result match { - case Full(true) => println("Access granted") - case Full(false) => println("Access denied") - case Failure(msg, _, _) => println(s"Error: $msg") - case Empty => println("Rule not found") - } -} -``` - -### Execute a Rule (Sync - Deprecated) -```scala -import code.abacrule.AbacRuleEngine -import com.openbankproject.commons.model._ - -// This is deprecated and blocks the thread - use async version above instead -val result = AbacRuleEngine.executeRuleSync( - ruleId = "rule123", - authenticatedUserId = currentUser.userId, - onBehalfOfUserId = None, - userId = Some(targetUser.userId), - callContext = callContext, - bankId = Some(bank.bankId.value), - accountId = Some(account.accountId.value), - viewId = None, - transactionId = None, - transactionRequestId = None, - customerId = None + user = currentUser, + bankOpt = Some(bank), + accountOpt = Some(account), + transactionOpt = None, + customerOpt = None ) result match { @@ -235,56 +199,24 @@ result match { } ``` -### Execute Rules by Policy (Async - Recommended) -Execute all active rules associated with a policy (OR logic - at least one must pass): +### Execute Multiple Rules (AND Logic) +All rules must pass: ```scala -val resultFuture: Future[Box[Boolean]] = AbacRuleEngine.executeRulesByPolicy( - policy = "account_access_policy", - authenticatedUserId = currentUser.userId, - onBehalfOfUserId = None, - userId = Some(targetUser.userId), - callContext = callContext, - bankId = Some(bank.bankId.value), - accountId = Some(account.accountId.value), - viewId = None, - transactionId = None, - transactionRequestId = None, - customerId = None +val result = AbacRuleEngine.executeRulesAnd( + ruleIds = List("rule1", "rule2", "rule3"), + user = currentUser, + bankOpt = Some(bank) ) - -resultFuture.map { result => - result match { - case Full(true) => println("Access granted by policy") - case Full(false) => println("Access denied by policy") - case Failure(msg, _, _) => println(s"Error: $msg") - case Empty => println("Policy not found") - } -} ``` -### Execute Rules by Policy (Sync - Deprecated) +### Execute Multiple Rules (OR Logic) +At least one rule must pass: ```scala -// This is deprecated and blocks the thread - use async version above instead -val result = AbacRuleEngine.executeRulesByPolicySync( - policy = "account_access_policy", - authenticatedUserId = currentUser.userId, - onBehalfOfUserId = None, - userId = Some(targetUser.userId), - callContext = callContext, - bankId = Some(bank.bankId.value), - accountId = Some(account.accountId.value), - viewId = None, - transactionId = None, - transactionRequestId = None, - customerId = None +val result = AbacRuleEngine.executeRulesOr( + ruleIds = List("rule1", "rule2", "rule3"), + user = currentUser, + bankOpt = Some(bank) ) - -result match { - case Full(true) => println("Access granted by policy") - case Full(false) => println("Access denied by policy") - case Failure(msg, _, _) => println(s"Error: $msg") - case Empty => println("Policy not found") -} ``` ### Validate Rule Code @@ -409,19 +341,16 @@ for { (account, callContext) <- NewStyle.function.getBankAccount(bankId, accountId, callContext) // Check ABAC rules - allowed <- AbacRuleEngine.executeRulesByPolicy( - policy = "bank_access_policy", - authenticatedUserId = user.userId, - onBehalfOfUserId = None, - userId = Some(user.userId), - callContext = callContext, - bankId = Some(bank.bankId.value), - accountId = Some(account.accountId.value), - viewId = None, - transactionId = None, - transactionRequestId = None, - customerId = None - ) + allowed <- Future { + AbacRuleEngine.executeRulesAnd( + ruleIds = List("bank_access_rule", "account_limit_rule"), + user = user, + bankOpt = Some(bank), + accountOpt = Some(account) + ) + } map { + unboxFullOrFail(_, callContext, "ABAC access check failed", 403) + } _ <- Helper.booleanToFuture(s"Access denied by ABAC rules", cc = callContext) { allowed From 1534831ff434964bdadf19981adb3b49dd429135 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marko=20Mili=C4=87?= Date: Fri, 23 Jan 2026 18:13:42 +0100 Subject: [PATCH 5/8] refactor/Refactor ResourceDocMiddleware: integrate JSON content type and improve validation DSL - Ensure all responses (errors and successful) have JSON Content-Type - Replace repeated EitherT patterns with a clean Validation DSL (success/failure) - Add ValidationContext to accumulate user, bank, account, view, and counterparty entities - Add detailed comments for authentication, authorization, and entity validation steps - Simplify middleware logic while preserving original validation order and behavior --- .../util/http4s/ResourceDocMiddleware.scala | 447 +++++++++--------- 1 file changed, 216 insertions(+), 231 deletions(-) diff --git a/obp-api/src/main/scala/code/api/util/http4s/ResourceDocMiddleware.scala b/obp-api/src/main/scala/code/api/util/http4s/ResourceDocMiddleware.scala index 878d398dd7..2b7876b88f 100644 --- a/obp-api/src/main/scala/code/api/util/http4s/ResourceDocMiddleware.scala +++ b/obp-api/src/main/scala/code/api/util/http4s/ResourceDocMiddleware.scala @@ -1,27 +1,26 @@ package code.api.util.http4s -import cats.data.{Kleisli, OptionT} +import cats.data.{EitherT, Kleisli, OptionT} import cats.effect._ import code.api.APIFailureNewStyle import code.api.util.APIUtil.ResourceDoc import code.api.util.ErrorMessages._ -import code.api.util.{APIUtil, CallContext, NewStyle} import code.api.util.newstyle.ViewNewStyle +import code.api.util.{APIUtil, CallContext, NewStyle} import code.util.Helper.MdcLoggable import com.openbankproject.commons.model._ -import net.liftweb.common.{Box, Empty, Full, Failure => LiftFailure} +import net.liftweb.common.{Box, Empty, Full} import org.http4s._ import org.http4s.headers.`Content-Type` import scala.collection.mutable.ArrayBuffer -import scala.language.higherKinds /** * ResourceDoc-driven validation middleware for http4s. - * + * * This middleware wraps http4s routes with automatic validation based on ResourceDoc metadata. * Validation is performed in a specific order to ensure security and proper error responses. - * + * * VALIDATION ORDER: * 1. Authentication - Check if user is authenticated (if required by ResourceDoc) * 2. Authorization - Verify user has required roles/entitlements @@ -29,18 +28,42 @@ import scala.language.higherKinds * 4. Account validation - Validate ACCOUNT_ID path parameter (if present) * 5. View validation - Validate VIEW_ID and check user access (if present) * 6. Counterparty validation - Validate COUNTERPARTY_ID (if present) - * + * * Validated entities are stored in CallContext fields for use in endpoint handlers. */ -object ResourceDocMiddleware extends MdcLoggable{ - +object ResourceDocMiddleware extends MdcLoggable { + + /** Type alias for http4s OptionT route effect */ type HttpF[A] = OptionT[IO, A] - type Middleware[F[_]] = HttpRoutes[F] => HttpRoutes[F] + + /** Type alias for validation effect using EitherT */ + type Validation[A] = EitherT[IO, Response[IO], A] + + /** JSON content type for responses */ private val jsonContentType: `Content-Type` = `Content-Type`(MediaType.application.json) - + + /** + * Context that accumulates all validated entities during request processing. + * This context is passed along the validation chain. + */ + final case class ValidationContext( + user: Box[User] = Empty, + callContext: CallContext, + bank: Option[Bank] = None, + account: Option[BankAccount] = None, + view: Option[View] = None, + counterparty: Option[CounterpartyTrait] = None + ) + + /** Simple DSL for success/failure in the validation chain */ + object DSL { + def success[A](a: A): Validation[A] = EitherT.rightT(a) + def failure(resp: Response[IO]): Validation[Nothing] = EitherT.leftT(resp) + } + /** * Check if ResourceDoc requires authentication. - * + * * Authentication is required if: * - ResourceDoc errorResponseBodies contains $AuthenticatedUserIsRequired * - ResourceDoc has roles (roles always require authenticated user) @@ -53,241 +76,203 @@ object ResourceDocMiddleware extends MdcLoggable{ resourceDoc.errorResponseBodies.contains($AuthenticatedUserIsRequired) || resourceDoc.roles.exists(_.nonEmpty) } } - + /** - * Create middleware that applies ResourceDoc-driven validation. - * - * @param resourceDocs Collection of ResourceDoc entries for matching - * @return Middleware that wraps HttpRoutes with validation + * Middleware factory: wraps HttpRoutes with ResourceDoc validation. + * Finds the matching ResourceDoc, validates the request, and enriches CallContext. */ - def apply(resourceDocs: ArrayBuffer[ResourceDoc]): Middleware[IO] = { routes => - Kleisli[HttpF, Request[IO], Response[IO]] { req => - OptionT(validateAndRoute(req, routes, resourceDocs).map(Option(_))) + def apply(resourceDocs: ArrayBuffer[ResourceDoc]): HttpRoutes[IO] => HttpRoutes[IO] = { routes => + Kleisli[HttpF, Request[IO], Response[IO]] { req: Request[IO] => + // Build initial CallContext from request + OptionT.liftF(Http4sCallContextBuilder.fromRequest(req, "v7.0.0")).flatMap { cc => + ResourceDocMatcher.findResourceDoc(req.method.name, req.uri.path, resourceDocs) match { + case Some(resourceDoc) => + val ccWithDoc = ResourceDocMatcher.attachToCallContext(cc, resourceDoc) + val pathParams = ResourceDocMatcher.extractPathParams(req.uri.path, resourceDoc) + // Run full validation chain + OptionT(validateRequest(req, resourceDoc, pathParams, ccWithDoc, routes).map(Option(_))) + + case None => + // No matching ResourceDoc: fallback to original route + routes.run(req) + } + } } } - + /** - * Validate request and route to handler if validation passes. - * - * Steps: - * 1. Build CallContext from request - * 2. Find matching ResourceDoc - * 3. Run validation chain - * 4. Route to handler with enriched CallContext + * Executes the full validation chain for the request. + * Returns either an error Response or enriched request routed to the handler. */ - private def validateAndRoute( - req: Request[IO], - routes: HttpRoutes[IO], - resourceDocs: ArrayBuffer[ResourceDoc] - ): IO[Response[IO]] = { - for { - cc <- Http4sCallContextBuilder.fromRequest(req, "v7.0.0") - resourceDocOpt = ResourceDocMatcher.findResourceDoc(req.method.name, req.uri.path, resourceDocs) - response <- resourceDocOpt match { - case Some(resourceDoc) => - val ccWithDoc = ResourceDocMatcher.attachToCallContext(cc, resourceDoc) - val pathParams = ResourceDocMatcher.extractPathParams(req.uri.path, resourceDoc) - runValidationChainForRoutes(req, resourceDoc, ccWithDoc, pathParams, routes) - .map(ensureJsonContentType) - case None => - routes.run(req).getOrElseF(IO.pure(Response[IO](org.http4s.Status.NotFound))) + private def validateRequest( + req: Request[IO], + resourceDoc: ResourceDoc, + pathParams: Map[String, String], + cc: CallContext, + routes: HttpRoutes[IO] + ): IO[Response[IO]] = { + + // Initial context with just CallContext + val initialCtx = ValidationContext(callContext = cc) + + // Compose all validation steps using EitherT + val result: Validation[ValidationContext] = for { + ctx1 <- authenticate(req, resourceDoc, initialCtx) + ctx2 <- authorizeRoles(resourceDoc, pathParams, ctx1) + ctx3 <- validateBank(pathParams, ctx2) + ctx4 <- validateAccount(pathParams, ctx3) + ctx5 <- validateView(pathParams, ctx4) + ctx6 <- validateCounterparty(pathParams, ctx5) + } yield ctx6 + + // Convert Validation result to Response + result.value.flatMap { + case Left(errorResponse) => IO.pure(ensureJsonContentType(errorResponse)) // Ensure all error responses are JSON + case Right(validCtx) => + // Enrich request with validated CallContext + val enrichedReq = req.withAttribute( + Http4sRequestAttributes.callContextKey, + validCtx.callContext.copy( + bank = validCtx.bank, + bankAccount = validCtx.account, + view = validCtx.view, + counterparty = validCtx.counterparty + ) + ) + routes.run(enrichedReq) + .map(ensureJsonContentType) // Ensure routed response has JSON content type + .getOrElseF(IO.pure(ensureJsonContentType(Response[IO](org.http4s.Status.NotFound)))) + } + } + + /** Authentication step: verifies user and updates ValidationContext */ + private def authenticate(req: Request[IO], resourceDoc: ResourceDoc, ctx: ValidationContext): Validation[ValidationContext] = { + val needsAuth = ResourceDocMiddleware.needsAuthentication(resourceDoc) + logger.debug(s"[ResourceDocMiddleware] needsAuthentication for ${resourceDoc.partialFunctionName}: $needsAuth") + + val io = + if (needsAuth) IO.fromFuture(IO(APIUtil.authenticatedAccess(ctx.callContext))) + else IO.fromFuture(IO(APIUtil.anonymousAccess(ctx.callContext))) + + EitherT( + io.attempt.flatMap { + case Right((boxUser, Some(updatedCC))) => + IO.pure(Right(ctx.copy(user = boxUser, callContext = updatedCC))) + case Right((boxUser, None)) => + IO.pure(Right(ctx.copy(user = boxUser))) + case Left(e: APIFailureNewStyle) => + ErrorResponseConverter.createErrorResponse(e.failCode, e.failMsg, ctx.callContext).map(Left(_)) + case Left(_) => + ErrorResponseConverter.createErrorResponse(401, $AuthenticatedUserIsRequired, ctx.callContext).map(Left(_)) } - } yield response + ) } - /** - * Ensure response has JSON content type. - */ - private def ensureJsonContentType(response: Response[IO]): Response[IO] = { - response.contentType match { - case Some(contentType) if contentType.mediaType == MediaType.application.json => response - case _ => response.withContentType(jsonContentType) + /** Role authorization step: ensures user has required roles */ + private def authorizeRoles(resourceDoc: ResourceDoc, pathParams: Map[String, String], ctx: ValidationContext): Validation[ValidationContext] = { + import DSL._ + + resourceDoc.roles match { + case Some(roles) if roles.nonEmpty => + ctx.user match { + case Full(user) => + val bankId = pathParams.getOrElse("BANK_ID", "") + val ok = roles.exists { role => + val checkBankId = if (role.requiresBankId) bankId else "" + APIUtil.hasEntitlement(checkBankId, user.userId, role) + } + if (ok) success(ctx) + else EitherT[IO, Response[IO], ValidationContext]( + ErrorResponseConverter.createErrorResponse(403, UserHasMissingRoles + roles.mkString(", "), ctx.callContext) + .map[Either[Response[IO], ValidationContext]](Left(_)) + ) + case _ => + EitherT[IO, Response[IO], ValidationContext]( + ErrorResponseConverter + .createErrorResponse(401, $AuthenticatedUserIsRequired, ctx.callContext) + .map[Either[Response[IO], ValidationContext]](resp => Left(resp)) + ) + } + case _ => success(ctx) } } - - /** - * Run validation chain for HttpRoutes and return Response. - * - * This method performs all validation steps in order: - * 1. Authentication (if required) - * 2. Role authorization (if roles specified) - * 3. Bank validation (if BANK_ID in path) - * 4. Account validation (if ACCOUNT_ID in path) - * 5. View validation (if VIEW_ID in path) - * 6. Counterparty validation (if COUNTERPARTY_ID in path) - * - * On success: Enriches CallContext with validated entities and routes to handler - * On failure: Returns error response immediately - */ - private def runValidationChainForRoutes( - req: Request[IO], - resourceDoc: ResourceDoc, - cc: CallContext, - pathParams: Map[String, String], - routes: HttpRoutes[IO] - ): IO[Response[IO]] = { - - val needsAuth = needsAuthentication(resourceDoc) - logger.debug(s"[ResourceDocMiddleware] needsAuthentication for ${resourceDoc.partialFunctionName}: $needsAuth") - - // Step 1: Authentication - val authResult: IO[Either[Response[IO], (Box[User], CallContext)]] = - if (needsAuth) { - IO.fromFuture(IO(APIUtil.authenticatedAccess(cc))).attempt.flatMap { - case Right((boxUser, optCC)) => - val updatedCC = optCC.getOrElse(cc) - boxUser match { - case Full(user) => - IO.pure(Right((boxUser, updatedCC))) - case Empty => - ErrorResponseConverter.createErrorResponse(401, $AuthenticatedUserIsRequired, updatedCC).map(Left(_)) - case LiftFailure(msg, _, _) => - ErrorResponseConverter.createErrorResponse(401, msg, updatedCC).map(Left(_)) + + /** Bank validation: checks BANK_ID and fetches bank */ + private def validateBank(pathParams: Map[String, String], ctx: ValidationContext): Validation[ValidationContext] = { + + pathParams.get("BANK_ID") match { + case Some(bankId) => + EitherT( + IO.fromFuture(IO(NewStyle.function.getBank(BankId(bankId), Some(ctx.callContext)))) + .attempt.flatMap { + case Right((bank, Some(updatedCC))) => IO.pure(Right(ctx.copy(bank = Some(bank), callContext = updatedCC))) + case Right((bank, None)) => IO.pure(Right(ctx.copy(bank = Some(bank)))) + case Left(e: APIFailureNewStyle) => ErrorResponseConverter.createErrorResponse(e.failCode, e.failMsg, ctx.callContext).map(Left(_)) + case Left(_) => ErrorResponseConverter.createErrorResponse(404, BankNotFound + s": $bankId", ctx.callContext).map(Left(_)) } - case Left(e: APIFailureNewStyle) => - ErrorResponseConverter.createErrorResponse(e.failCode, e.failMsg, cc).map(Left(_)) - case Left(e) => - val (code, msg) = try { - import net.liftweb.json._ - implicit val formats = net.liftweb.json.DefaultFormats - val json = parse(e.getMessage) - val failCode = (json \ "failCode").extractOpt[Int].getOrElse(401) - val failMsg = (json \ "failMsg").extractOpt[String].getOrElse($AuthenticatedUserIsRequired) - (failCode, failMsg) - } catch { - case _: Exception => (401, $AuthenticatedUserIsRequired) + ) + case None => DSL.success(ctx) + } + } + + /** Account validation: checks ACCOUNT_ID and fetches bank account */ + private def validateAccount(pathParams: Map[String, String], ctx: ValidationContext): Validation[ValidationContext] = { + + (pathParams.get("BANK_ID"), pathParams.get("ACCOUNT_ID")) match { + case (Some(bankId), Some(accountId)) => + EitherT( + IO.fromFuture(IO(NewStyle.function.getBankAccount(BankId(bankId), AccountId(accountId), Some(ctx.callContext)))) + .attempt.flatMap { + case Right((acc, Some(updatedCC))) => IO.pure(Right(ctx.copy(account = Some(acc), callContext = updatedCC))) + case Right((acc, None)) => IO.pure(Right(ctx.copy(account = Some(acc)))) + case Left(e: APIFailureNewStyle) => ErrorResponseConverter.createErrorResponse(e.failCode, e.failMsg, ctx.callContext).map(Left(_)) + case Left(_) => ErrorResponseConverter.createErrorResponse(404, BankAccountNotFound + s": bankId=$bankId, accountId=$accountId", ctx.callContext).map(Left(_)) } - ErrorResponseConverter.createErrorResponse(code, msg, cc).map(Left(_)) - } - } else { - IO.fromFuture(IO(APIUtil.anonymousAccess(cc))).attempt.flatMap { - case Right((boxUser, Some(updatedCC))) => - IO.pure(Right((boxUser, updatedCC))) - case Right((boxUser, None)) => - IO.pure(Right((boxUser, cc))) - case Left(e) => - // For anonymous endpoints, continue with Empty user even if auth fails - IO.pure(Right((Empty, cc))) - } - } + ) + case _ => DSL.success(ctx) + } + } - authResult.flatMap { - case Left(errorResponse) => IO.pure(errorResponse) - case Right((boxUser, cc1)) => - // Step 2: Role authorization - val rolesResult: IO[Either[Response[IO], CallContext]] = - resourceDoc.roles match { - case Some(roles) if roles.nonEmpty => - boxUser match { - case Full(user) => - val userId = user.userId - val bankId = pathParams.get("BANK_ID").getOrElse("") - val hasRole = roles.exists { role => - val checkBankId = if (role.requiresBankId) bankId else "" - APIUtil.hasEntitlement(checkBankId, userId, role) - } - if (hasRole) IO.pure(Right(cc1)) - else ErrorResponseConverter.createErrorResponse(403, UserHasMissingRoles + roles.mkString(", "), cc1).map(Left(_)) - case _ => - ErrorResponseConverter.createErrorResponse(401, $AuthenticatedUserIsRequired, cc1).map(Left(_)) - } - case _ => IO.pure(Right(cc1)) - } - - rolesResult.flatMap { - case Left(errorResponse) => IO.pure(errorResponse) - case Right(cc2) => - // Step 3: Bank validation - val bankResult: IO[Either[Response[IO], (Option[Bank], CallContext)]] = - pathParams.get("BANK_ID") match { - case Some(bankIdStr) => - IO.fromFuture(IO(NewStyle.function.getBank(BankId(bankIdStr), Some(cc2)))).attempt.flatMap { - case Right((bank, Some(updatedCC))) => - IO.pure(Right((Some(bank), updatedCC))) - case Right((bank, None)) => - IO.pure(Right((Some(bank), cc2))) - case Left(e: APIFailureNewStyle) => - ErrorResponseConverter.createErrorResponse(e.failCode, e.failMsg, cc2).map(Left(_)) - case Left(e) => - ErrorResponseConverter.createErrorResponse(404, BankNotFound + ": " + bankIdStr, cc2).map(Left(_)) - } - case None => IO.pure(Right((None, cc2))) - } - - bankResult.flatMap { - case Left(errorResponse) => IO.pure(errorResponse) - case Right((bankOpt, cc3)) => - // Step 4: Account validation (if ACCOUNT_ID in path) - val accountResult: IO[Either[Response[IO], (Option[BankAccount], CallContext)]] = - (pathParams.get("BANK_ID"), pathParams.get("ACCOUNT_ID")) match { - case (Some(bankIdStr), Some(accountIdStr)) => - IO.fromFuture(IO(NewStyle.function.getBankAccount(BankId(bankIdStr), AccountId(accountIdStr), Some(cc3)))).attempt.flatMap { - case Right((account, Some(updatedCC))) => IO.pure(Right((Some(account), updatedCC))) - case Right((account, None)) => IO.pure(Right((Some(account), cc3))) - case Left(e: APIFailureNewStyle) => - ErrorResponseConverter.createErrorResponse(e.failCode, e.failMsg, cc3).map(Left(_)) - case Left(e) => - ErrorResponseConverter.createErrorResponse(404, BankAccountNotFound + s": bankId=$bankIdStr, accountId=$accountIdStr", cc3).map(Left(_)) - } - case _ => IO.pure(Right((None, cc3))) - } + /** View validation: checks VIEW_ID and user access */ + private def validateView(pathParams: Map[String, String], ctx: ValidationContext): Validation[ValidationContext] = { - - accountResult.flatMap { - case Left(errorResponse) => IO.pure(errorResponse) - case Right((accountOpt, cc4)) => - // Step 5: View validation (if VIEW_ID in path) - val viewResult: IO[Either[Response[IO], (Option[View], CallContext)]] = - (pathParams.get("BANK_ID"), pathParams.get("ACCOUNT_ID"), pathParams.get("VIEW_ID")) match { - case (Some(bankIdStr), Some(accountIdStr), Some(viewIdStr)) => - val bankIdAccountId = BankIdAccountId(BankId(bankIdStr), AccountId(accountIdStr)) - IO.fromFuture(IO(ViewNewStyle.checkViewAccessAndReturnView(ViewId(viewIdStr), bankIdAccountId, boxUser.toOption, Some(cc4)))).attempt.flatMap { - case Right(view) => IO.pure(Right((Some(view), cc4))) - case Left(e: APIFailureNewStyle) => - ErrorResponseConverter.createErrorResponse(e.failCode, e.failMsg, cc4).map(Left(_)) - case Left(e) => - ErrorResponseConverter.createErrorResponse(403, UserNoPermissionAccessView + s": viewId=$viewIdStr", cc4).map(Left(_)) - } - case _ => IO.pure(Right((None, cc4))) - } - - viewResult.flatMap { - case Left(errorResponse) => IO.pure(errorResponse) - case Right((viewOpt, cc5)) => - // Step 6: Counterparty validation (if COUNTERPARTY_ID in path) - val counterpartyResult: IO[Either[Response[IO], (Option[CounterpartyTrait], CallContext)]] = - (pathParams.get("BANK_ID"), pathParams.get("ACCOUNT_ID"), pathParams.get("COUNTERPARTY_ID")) match { - case (Some(bankIdStr), Some(accountIdStr), Some(counterpartyIdStr)) => - IO.fromFuture(IO(NewStyle.function.getCounterpartyTrait(BankId(bankIdStr), AccountId(accountIdStr), counterpartyIdStr, Some(cc5)))).attempt.flatMap { - case Right((counterparty, Some(updatedCC))) => IO.pure(Right((Some(counterparty), updatedCC))) - case Right((counterparty, None)) => IO.pure(Right((Some(counterparty), cc5))) - case Left(e: APIFailureNewStyle) => - ErrorResponseConverter.createErrorResponse(e.failCode, e.failMsg, cc5).map(Left(_)) - case Left(e) => - ErrorResponseConverter.createErrorResponse(404, CounterpartyNotFound + s": counterpartyId=$counterpartyIdStr", cc5).map(Left(_)) - } - case _ => IO.pure(Right((None, cc5))) - } - - counterpartyResult.flatMap { - case Left(errorResponse) => IO.pure(errorResponse) - case Right((counterpartyOpt, finalCC)) => - // All validations passed - update CallContext with validated entities - val enrichedCC = finalCC.copy( - bank = bankOpt, - bankAccount = accountOpt, - view = viewOpt, - counterparty = counterpartyOpt - ) - - // Store enriched CallContext in request attributes - val updatedReq = req.withAttribute(Http4sRequestAttributes.callContextKey, enrichedCC) - routes.run(updatedReq).getOrElseF(IO.pure(Response[IO](org.http4s.Status.NotFound))) - } - } - } + (pathParams.get("BANK_ID"), pathParams.get("ACCOUNT_ID"), pathParams.get("VIEW_ID")) match { + case (Some(bankId), Some(accountId), Some(viewId)) => + EitherT( + IO.fromFuture(IO(ViewNewStyle.checkViewAccessAndReturnView(ViewId(viewId), BankIdAccountId(BankId(bankId), AccountId(accountId)), ctx.user.toOption, Some(ctx.callContext)))) + .attempt.flatMap { + case Right(view) => IO.pure(Right(ctx.copy(view = Some(view)))) + case Left(e: APIFailureNewStyle) => ErrorResponseConverter.createErrorResponse(e.failCode, e.failMsg, ctx.callContext).map(Left(_)) + case Left(_) => ErrorResponseConverter.createErrorResponse(403, UserNoPermissionAccessView + s": viewId=$viewId", ctx.callContext).map(Left(_)) } - } + ) + case _ => DSL.success(ctx) + } + } + + /** Counterparty validation: checks COUNTERPARTY_ID and fetches counterparty */ + private def validateCounterparty(pathParams: Map[String, String], ctx: ValidationContext): Validation[ValidationContext] = { + + (pathParams.get("BANK_ID"), pathParams.get("ACCOUNT_ID"), pathParams.get("COUNTERPARTY_ID")) match { + case (Some(bankId), Some(accountId), Some(counterpartyId)) => + EitherT( + IO.fromFuture(IO(NewStyle.function.getCounterpartyTrait(BankId(bankId), AccountId(accountId), counterpartyId, Some(ctx.callContext)))) + .attempt.flatMap { + case Right((cp, Some(updatedCC))) => IO.pure(Right(ctx.copy(counterparty = Some(cp), callContext = updatedCC))) + case Right((cp, None)) => IO.pure(Right(ctx.copy(counterparty = Some(cp)))) + case Left(e: APIFailureNewStyle) => ErrorResponseConverter.createErrorResponse(e.failCode, e.failMsg, ctx.callContext).map(Left(_)) + case Left(_) => ErrorResponseConverter.createErrorResponse(404, CounterpartyNotFound + s": counterpartyId=$counterpartyId", ctx.callContext).map(Left(_)) + } + ) + case _ => DSL.success(ctx) + } + } + + /** Ensure the response has JSON content type */ + private def ensureJsonContentType(response: Response[IO]): Response[IO] = { + response.contentType match { + case Some(contentType) if contentType.mediaType == MediaType.application.json => response + case _ => response.withContentType(jsonContentType) } } } From 0188ba61a06016a98acc567e3a9fd4f3c51464b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marko=20Mili=C4=87?= Date: Mon, 26 Jan 2026 10:25:36 +0100 Subject: [PATCH 6/8] refactor/Tweak variables names --- .../api/util/http4s/ResourceDocMiddleware.scala | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/obp-api/src/main/scala/code/api/util/http4s/ResourceDocMiddleware.scala b/obp-api/src/main/scala/code/api/util/http4s/ResourceDocMiddleware.scala index 2b7876b88f..cee52b861e 100644 --- a/obp-api/src/main/scala/code/api/util/http4s/ResourceDocMiddleware.scala +++ b/obp-api/src/main/scala/code/api/util/http4s/ResourceDocMiddleware.scala @@ -113,17 +113,17 @@ object ResourceDocMiddleware extends MdcLoggable { ): IO[Response[IO]] = { // Initial context with just CallContext - val initialCtx = ValidationContext(callContext = cc) + val initialContext = ValidationContext(callContext = cc) // Compose all validation steps using EitherT val result: Validation[ValidationContext] = for { - ctx1 <- authenticate(req, resourceDoc, initialCtx) - ctx2 <- authorizeRoles(resourceDoc, pathParams, ctx1) - ctx3 <- validateBank(pathParams, ctx2) - ctx4 <- validateAccount(pathParams, ctx3) - ctx5 <- validateView(pathParams, ctx4) - ctx6 <- validateCounterparty(pathParams, ctx5) - } yield ctx6 + context <- authenticate(req, resourceDoc, initialContext) + context <- authorizeRoles(resourceDoc, pathParams, context) + context <- validateBank(pathParams, context) + context <- validateAccount(pathParams, context) + context <- validateView(pathParams, context) + context <- validateCounterparty(pathParams, context) + } yield context // Convert Validation result to Response result.value.flatMap { From 18daf8dfb226424f4157af015564b602fab1a985 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marko=20Mili=C4=87?= Date: Mon, 26 Jan 2026 12:42:31 +0100 Subject: [PATCH 7/8] Revert "fix Github Action" This reverts commit 3a264ed32676adbd2a761a6125cb2b09f120e61e. --- .github/workflows/auto_update_base_image.yml | 35 ++++++ .../build_container_develop_branch.yml | 31 +++++ .../build_container_non_develop_branch.yml | 114 ++++++++++++++++++ .github/workflows/build_pull_request.yml | 87 +++++++++++++ .github/workflows/run_trivy.yml | 54 +++++++++ 5 files changed, 321 insertions(+) create mode 100644 .github/workflows/auto_update_base_image.yml create mode 100644 .github/workflows/build_container_non_develop_branch.yml create mode 100644 .github/workflows/build_pull_request.yml create mode 100644 .github/workflows/run_trivy.yml diff --git a/.github/workflows/auto_update_base_image.yml b/.github/workflows/auto_update_base_image.yml new file mode 100644 index 0000000000..3048faf15e --- /dev/null +++ b/.github/workflows/auto_update_base_image.yml @@ -0,0 +1,35 @@ +name: Regular base image update check +on: + schedule: + - cron: "0 5 * * *" + workflow_dispatch: + +env: + ## Sets environment variable + DOCKER_HUB_ORGANIZATION: ${{ vars.DOCKER_HUB_ORGANIZATION }} + +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Docker Image Update Checker + id: baseupdatecheck + uses: lucacome/docker-image-update-checker@v2.0.0 + with: + base-image: jetty:9.4-jdk11-alpine + image: ${{ env.DOCKER_HUB_ORGANIZATION }}/obp-api:latest + + - name: Trigger build_container_develop_branch workflow + uses: actions/github-script@v6 + with: + script: | + await github.rest.actions.createWorkflowDispatch({ + owner: context.repo.owner, + repo: context.repo.repo, + workflow_id: 'build_container_develop_branch.yml', + ref: 'refs/heads/develop' + }); + if: steps.baseupdatecheck.outputs.needs-updating == 'true' diff --git a/.github/workflows/build_container_develop_branch.yml b/.github/workflows/build_container_develop_branch.yml index 3dfbad23d8..4f82e563bd 100644 --- a/.github/workflows/build_container_develop_branch.yml +++ b/.github/workflows/build_container_develop_branch.yml @@ -124,3 +124,34 @@ jobs: with: name: ${{ github.sha }} path: push/ + + - name: Build the Docker image + run: | + echo "${{ secrets.DOCKER_HUB_TOKEN }}" | docker login -u "${{ secrets.DOCKER_HUB_USERNAME }}" --password-stdin docker.io + docker build . --file .github/Dockerfile_PreBuild --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:$GITHUB_SHA --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:latest --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:develop + docker build . --file .github/Dockerfile_PreBuild_OC --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:$GITHUB_SHA-OC --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:latest-OC --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:develop-OC --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:${GITHUB_REF##*/}-OC + docker push docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }} --all-tags + echo docker done + + - uses: sigstore/cosign-installer@main + + - name: Write signing key to disk (only needed for `cosign sign --key`) + run: echo "${{ secrets.COSIGN_PRIVATE_KEY }}" > cosign.key + + - name: Sign container image + run: | + cosign sign -y --key cosign.key \ + docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:develop + cosign sign -y --key cosign.key \ + docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:latest + cosign sign -y --key cosign.key \ + docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:$GITHUB_SHA + cosign sign -y --key cosign.key \ + docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:develop-OC + cosign sign -y --key cosign.key \ + docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:latest-OC + env: + COSIGN_PASSWORD: "${{secrets.COSIGN_PASSWORD}}" + + + diff --git a/.github/workflows/build_container_non_develop_branch.yml b/.github/workflows/build_container_non_develop_branch.yml new file mode 100644 index 0000000000..946d81de4d --- /dev/null +++ b/.github/workflows/build_container_non_develop_branch.yml @@ -0,0 +1,114 @@ +name: Build and publish container non develop + +on: + push: + branches: + - '*' + - '!develop' + +env: + DOCKER_HUB_ORGANIZATION: ${{ vars.DOCKER_HUB_ORGANIZATION }} + DOCKER_HUB_REPOSITORY: obp-api + +jobs: + build: + runs-on: ubuntu-latest + services: + # Label used to access the service container + redis: + # Docker Hub image + image: redis + ports: + # Opens tcp port 6379 on the host and service container + - 6379:6379 + # Set health checks to wait until redis has started + options: >- + --health-cmd "redis-cli ping" + --health-interval 10s + --health-timeout 5s + --health-retries 5 + steps: + - uses: actions/checkout@v4 + - name: Extract branch name + shell: bash + run: echo "branch=${GITHUB_HEAD_REF:-${GITHUB_REF#refs/heads/}}" + - name: Set up JDK 11 + uses: actions/setup-java@v4 + with: + java-version: '11' + distribution: 'adopt' + cache: maven + - name: Build with Maven + run: | + cp obp-api/src/main/resources/props/sample.props.template obp-api/src/main/resources/props/production.default.props + echo connector=star > obp-api/src/main/resources/props/test.default.props + echo starConnector_supported_types=mapped,internal >> obp-api/src/main/resources/props/test.default.props + echo hostname=http://localhost:8016 >> obp-api/src/main/resources/props/test.default.props + echo tests.port=8016 >> obp-api/src/main/resources/props/test.default.props + echo End of minimum settings >> obp-api/src/main/resources/props/test.default.props + echo payments_enabled=false >> obp-api/src/main/resources/props/test.default.props + echo importer_secret=change_me >> obp-api/src/main/resources/props/test.default.props + echo messageQueue.updateBankAccountsTransaction=false >> obp-api/src/main/resources/props/test.default.props + echo messageQueue.createBankAccounts=false >> obp-api/src/main/resources/props/test.default.props + echo allow_sandbox_account_creation=true >> obp-api/src/main/resources/props/test.default.props + echo allow_sandbox_data_import=true >> obp-api/src/main/resources/props/test.default.props + echo sandbox_data_import_secret=change_me >> obp-api/src/main/resources/props/test.default.props + echo allow_account_deletion=true >> obp-api/src/main/resources/props/test.default.props + echo allowed_internal_redirect_urls = /,/oauth/authorize >> obp-api/src/main/resources/props/test.default.props + echo transactionRequests_enabled=true >> obp-api/src/main/resources/props/test.default.props + echo transactionRequests_supported_types=SEPA,SANDBOX_TAN,FREE_FORM,COUNTERPARTY,ACCOUNT,SIMPLE >> obp-api/src/main/resources/props/test.default.props + echo SIMPLE_OTP_INSTRUCTION_TRANSPORT=dummy >> obp-api/src/main/resources/props/test.default.props + echo openredirects.hostname.whitlelist=http://127.0.0.1,http://localhost >> obp-api/src/main/resources/props/test.default.props + echo remotedata.secret = foobarbaz >> obp-api/src/main/resources/props/test.default.props + echo allow_public_views=true >> obp-api/src/main/resources/props/test.default.props + + echo SIMPLE_OTP_INSTRUCTION_TRANSPORT=dummy >> obp-api/src/main/resources/props/test.default.props + echo ACCOUNT_OTP_INSTRUCTION_TRANSPORT=dummy >> obp-api/src/main/resources/props/test.default.props + echo SEPA_OTP_INSTRUCTION_TRANSPORT=dummy >> obp-api/src/main/resources/props/test.default.props + echo FREE_FORM_OTP_INSTRUCTION_TRANSPORT=dummy >> obp-api/src/main/resources/props/test.default.props + echo COUNTERPARTY_OTP_INSTRUCTION_TRANSPORT=dummy >> obp-api/src/main/resources/props/test.default.props + echo SEPA_CREDIT_TRANSFERS_OTP_INSTRUCTION_TRANSPORT=dummy >> obp-api/src/main/resources/props/test.default.props + + echo allow_oauth2_login=true >> obp-api/src/main/resources/props/test.default.props + echo oauth2.jwk_set.url=https://www.googleapis.com/oauth2/v3/certs >> obp-api/src/main/resources/props/test.default.props + + echo ResetPasswordUrlEnabled=true >> obp-api/src/main/resources/props/test.default.props + + echo consents.allowed=true >> obp-api/src/main/resources/props/test.default.props + MAVEN_OPTS="-Xmx3G -Xss2m" mvn clean package -Pprod + + - name: Save .war artifact + run: | + mkdir -p ./push + cp obp-api/target/obp-api-1.*.war ./push/ + - uses: actions/upload-artifact@v4 + with: + name: ${{ github.sha }} + path: push/ + + - name: Build the Docker image + run: | + echo "${{ secrets.DOCKER_HUB_TOKEN }}" | docker login -u "${{ secrets.DOCKER_HUB_USERNAME }}" --password-stdin docker.io + docker build . --file .github/Dockerfile_PreBuild --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:$GITHUB_SHA --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:${GITHUB_REF##*/} + docker build . --file .github/Dockerfile_PreBuild_OC --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:$GITHUB_SHA-OC --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:${GITHUB_REF##*/}-OC + docker push docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }} --all-tags + echo docker done + + - uses: sigstore/cosign-installer@main + + - name: Write signing key to disk (only needed for `cosign sign --key`) + run: echo "${{ secrets.COSIGN_PRIVATE_KEY }}" > cosign.key + + - name: Sign container image + run: | + cosign sign -y --key cosign.key \ + docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:${GITHUB_REF##*/} + cosign sign -y --key cosign.key \ + docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:${GITHUB_REF##*/}-OC + cosign sign -y --key cosign.key \ + docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:$GITHUB_SHA + env: + COSIGN_PASSWORD: "${{secrets.COSIGN_PASSWORD}}" + + + diff --git a/.github/workflows/build_pull_request.yml b/.github/workflows/build_pull_request.yml new file mode 100644 index 0000000000..859d309ec2 --- /dev/null +++ b/.github/workflows/build_pull_request.yml @@ -0,0 +1,87 @@ +name: Build on Pull Request + +on: + pull_request: + branches: + - '**' +env: + ## Sets environment variable + DOCKER_HUB_ORGANIZATION: ${{ vars.DOCKER_HUB_ORGANIZATION }} + + +jobs: + build: + runs-on: ubuntu-latest + services: + # Label used to access the service container + redis: + # Docker Hub image + image: redis + ports: + # Opens tcp port 6379 on the host and service container + - 6379:6379 + # Set health checks to wait until redis has started + options: >- + --health-cmd "redis-cli ping" + --health-interval 10s + --health-timeout 5s + --health-retries 5 + steps: + - uses: actions/checkout@v4 + - name: Set up JDK 11 + uses: actions/setup-java@v4 + with: + java-version: '11' + distribution: 'adopt' + cache: maven + - name: Build with Maven + run: | + cp obp-api/src/main/resources/props/sample.props.template obp-api/src/main/resources/props/production.default.props + echo connector=star > obp-api/src/main/resources/props/test.default.props + echo starConnector_supported_types=mapped,internal >> obp-api/src/main/resources/props/test.default.props + echo hostname=http://localhost:8016 >> obp-api/src/main/resources/props/test.default.props + echo tests.port=8016 >> obp-api/src/main/resources/props/test.default.props + echo End of minimum settings >> obp-api/src/main/resources/props/test.default.props + echo payments_enabled=false >> obp-api/src/main/resources/props/test.default.props + echo importer_secret=change_me >> obp-api/src/main/resources/props/test.default.props + echo messageQueue.updateBankAccountsTransaction=false >> obp-api/src/main/resources/props/test.default.props + echo messageQueue.createBankAccounts=false >> obp-api/src/main/resources/props/test.default.props + echo allow_sandbox_account_creation=true >> obp-api/src/main/resources/props/test.default.props + echo allow_sandbox_data_import=true >> obp-api/src/main/resources/props/test.default.props + echo sandbox_data_import_secret=change_me >> obp-api/src/main/resources/props/test.default.props + echo allow_account_deletion=true >> obp-api/src/main/resources/props/test.default.props + echo allowed_internal_redirect_urls = /,/oauth/authorize >> obp-api/src/main/resources/props/test.default.props + echo transactionRequests_enabled=true >> obp-api/src/main/resources/props/test.default.props + echo transactionRequests_supported_types=SEPA,SANDBOX_TAN,FREE_FORM,COUNTERPARTY,ACCOUNT,SIMPLE >> obp-api/src/main/resources/props/test.default.props + echo SIMPLE_OTP_INSTRUCTION_TRANSPORT=dummy >> obp-api/src/main/resources/props/test.default.props + echo openredirects.hostname.whitlelist=http://127.0.0.1,http://localhost >> obp-api/src/main/resources/props/test.default.props + echo remotedata.secret = foobarbaz >> obp-api/src/main/resources/props/test.default.props + echo allow_public_views=true >> obp-api/src/main/resources/props/test.default.props + + echo SIMPLE_OTP_INSTRUCTION_TRANSPORT=dummy >> obp-api/src/main/resources/props/test.default.props + echo ACCOUNT_OTP_INSTRUCTION_TRANSPORT=dummy >> obp-api/src/main/resources/props/test.default.props + echo SEPA_OTP_INSTRUCTION_TRANSPORT=dummy >> obp-api/src/main/resources/props/test.default.props + echo FREE_FORM_OTP_INSTRUCTION_TRANSPORT=dummy >> obp-api/src/main/resources/props/test.default.props + echo COUNTERPARTY_OTP_INSTRUCTION_TRANSPORT=dummy >> obp-api/src/main/resources/props/test.default.props + echo SEPA_CREDIT_TRANSFERS_OTP_INSTRUCTION_TRANSPORT=dummy >> obp-api/src/main/resources/props/test.default.props + + + echo allow_oauth2_login=true >> obp-api/src/main/resources/props/test.default.props + echo oauth2.jwk_set.url=https://www.googleapis.com/oauth2/v3/certs >> obp-api/src/main/resources/props/test.default.props + + echo ResetPasswordUrlEnabled=true >> obp-api/src/main/resources/props/test.default.props + + echo consents.allowed=true >> obp-api/src/main/resources/props/test.default.props + MAVEN_OPTS="-Xmx3G -Xss2m" mvn clean package -Pprod + + - name: Save .war artifact + run: | + mkdir -p ./pull + cp obp-api/target/obp-api-1.*.war ./pull/ + - uses: actions/upload-artifact@v4 + with: + name: ${{ github.sha }} + path: pull/ + + + diff --git a/.github/workflows/run_trivy.yml b/.github/workflows/run_trivy.yml new file mode 100644 index 0000000000..4636bd3116 --- /dev/null +++ b/.github/workflows/run_trivy.yml @@ -0,0 +1,54 @@ +name: scan container image + +on: + workflow_run: + workflows: + - Build and publish container develop + - Build and publish container non develop + types: + - completed +env: + ## Sets environment variable + DOCKER_HUB_ORGANIZATION: ${{ vars.DOCKER_HUB_ORGANIZATION }} + DOCKER_HUB_REPOSITORY: obp-api + + +jobs: + build: + runs-on: ubuntu-latest + if: ${{ github.event.workflow_run.conclusion == 'success' }} + + steps: + - uses: actions/checkout@v4 + - id: trivy-db + name: Check trivy db sha + env: + GH_TOKEN: ${{ github.token }} + run: | + endpoint='/orgs/aquasecurity/packages/container/trivy-db/versions' + headers='Accept: application/vnd.github+json' + jqFilter='.[] | select(.metadata.container.tags[] | contains("latest")) | .name | sub("sha256:";"")' + sha=$(gh api -H "${headers}" "${endpoint}" | jq --raw-output "${jqFilter}") + echo "Trivy DB sha256:${sha}" + echo "::set-output name=sha::${sha}" + - uses: actions/cache@v4 + with: + path: .trivy + key: ${{ runner.os }}-trivy-db-${{ steps.trivy-db.outputs.sha }} + - name: Run Trivy vulnerability scanner + uses: aquasecurity/trivy-action@master + with: + image-ref: 'docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:${{ github.sha }}' + format: 'template' + template: '@/contrib/sarif.tpl' + output: 'trivy-results.sarif' + security-checks: 'vuln' + severity: 'CRITICAL,HIGH' + timeout: '30m' + cache-dir: .trivy + - name: Fix .trivy permissions + run: sudo chown -R $(stat . -c %u:%g) .trivy + - name: Upload Trivy scan results to GitHub Security tab + uses: github/codeql-action/upload-sarif@v3 + with: + sarif_file: 'trivy-results.sarif' \ No newline at end of file From 87b48fc71d935b57778bea8284ea1582d75e5264 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marko=20Mili=C4=87?= Date: Mon, 26 Jan 2026 12:54:28 +0100 Subject: [PATCH 8/8] feature/Tweak GitHub workflows --- .github/workflows/auto_update_base_image.yml | 3 +- .../build_container_develop_branch.yml | 15 +++-- .../build_container_non_develop_branch.yml | 58 +++++++++++++++---- .github/workflows/build_pull_request.yml | 54 +++++++++++++---- .github/workflows/run_trivy.yml | 19 +++--- 5 files changed, 110 insertions(+), 39 deletions(-) diff --git a/.github/workflows/auto_update_base_image.yml b/.github/workflows/auto_update_base_image.yml index 3048faf15e..e47d6d95bc 100644 --- a/.github/workflows/auto_update_base_image.yml +++ b/.github/workflows/auto_update_base_image.yml @@ -11,6 +11,7 @@ env: jobs: build: runs-on: ubuntu-latest + if: github.repository == 'OpenBankProject/OBP-API' steps: - name: Checkout repository uses: actions/checkout@v4 @@ -32,4 +33,4 @@ jobs: workflow_id: 'build_container_develop_branch.yml', ref: 'refs/heads/develop' }); - if: steps.baseupdatecheck.outputs.needs-updating == 'true' + if: steps.baseupdatecheck.outputs.needs-updating == 'true' \ No newline at end of file diff --git a/.github/workflows/build_container_develop_branch.yml b/.github/workflows/build_container_develop_branch.yml index 4f82e563bd..1fc605d172 100644 --- a/.github/workflows/build_container_develop_branch.yml +++ b/.github/workflows/build_container_develop_branch.yml @@ -13,7 +13,6 @@ env: DOCKER_HUB_ORGANIZATION: ${{ vars.DOCKER_HUB_ORGANIZATION }} DOCKER_HUB_REPOSITORY: obp-api - jobs: build: runs-on: ubuntu-latest @@ -36,8 +35,8 @@ jobs: - name: Set up JDK 11 uses: actions/setup-java@v4 with: - java-version: '11' - distribution: 'adopt' + java-version: "11" + distribution: "adopt" cache: maven - name: Build with Maven run: | @@ -126,6 +125,7 @@ jobs: path: push/ - name: Build the Docker image + if: github.repository == 'OpenBankProject/OBP-API' run: | echo "${{ secrets.DOCKER_HUB_TOKEN }}" | docker login -u "${{ secrets.DOCKER_HUB_USERNAME }}" --password-stdin docker.io docker build . --file .github/Dockerfile_PreBuild --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:$GITHUB_SHA --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:latest --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:develop @@ -133,12 +133,14 @@ jobs: docker push docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }} --all-tags echo docker done - - uses: sigstore/cosign-installer@main + - uses: sigstore/cosign-installer@4d14d7f17e7112af04ea6108fbb4bfc714c00390 - name: Write signing key to disk (only needed for `cosign sign --key`) + if: github.repository == 'OpenBankProject/OBP-API' run: echo "${{ secrets.COSIGN_PRIVATE_KEY }}" > cosign.key - name: Sign container image + if: github.repository == 'OpenBankProject/OBP-API' run: | cosign sign -y --key cosign.key \ docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:develop @@ -151,7 +153,4 @@ jobs: cosign sign -y --key cosign.key \ docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:latest-OC env: - COSIGN_PASSWORD: "${{secrets.COSIGN_PASSWORD}}" - - - + COSIGN_PASSWORD: "${{secrets.COSIGN_PASSWORD}}" \ No newline at end of file diff --git a/.github/workflows/build_container_non_develop_branch.yml b/.github/workflows/build_container_non_develop_branch.yml index 946d81de4d..61e8bfcd23 100644 --- a/.github/workflows/build_container_non_develop_branch.yml +++ b/.github/workflows/build_container_non_develop_branch.yml @@ -3,8 +3,8 @@ name: Build and publish container non develop on: push: branches: - - '*' - - '!develop' + - "*" + - "!develop" env: DOCKER_HUB_ORGANIZATION: ${{ vars.DOCKER_HUB_ORGANIZATION }} @@ -35,11 +35,12 @@ jobs: - name: Set up JDK 11 uses: actions/setup-java@v4 with: - java-version: '11' - distribution: 'adopt' + java-version: "11" + distribution: "adopt" cache: maven - name: Build with Maven run: | + set -o pipefail cp obp-api/src/main/resources/props/sample.props.template obp-api/src/main/resources/props/production.default.props echo connector=star > obp-api/src/main/resources/props/test.default.props echo starConnector_supported_types=mapped,internal >> obp-api/src/main/resources/props/test.default.props @@ -75,7 +76,44 @@ jobs: echo ResetPasswordUrlEnabled=true >> obp-api/src/main/resources/props/test.default.props echo consents.allowed=true >> obp-api/src/main/resources/props/test.default.props - MAVEN_OPTS="-Xmx3G -Xss2m" mvn clean package -Pprod + MAVEN_OPTS="-Xmx3G -Xss2m" mvn clean package -Pprod 2>&1 | tee maven-build.log + + - name: Report failing tests (if any) + if: always() + run: | + echo "Checking build log for failing tests via grep..." + if [ ! -f maven-build.log ]; then + echo "No maven-build.log found; skipping failure scan." + exit 0 + fi + if grep -n "\*\*\* FAILED \*\*\*" maven-build.log; then + echo "Failing tests detected above." + exit 1 + else + echo "No failing tests detected in maven-build.log." + fi + + - name: Upload Maven build log + if: always() + uses: actions/upload-artifact@v4 + with: + name: maven-build-log + if-no-files-found: ignore + path: | + maven-build.log + + - name: Upload test reports + if: always() + uses: actions/upload-artifact@v4 + with: + name: test-reports + if-no-files-found: ignore + path: | + obp-api/target/surefire-reports/** + obp-commons/target/surefire-reports/** + **/target/scalatest-reports/** + **/target/site/surefire-report.html + **/target/site/surefire-report/* - name: Save .war artifact run: | @@ -87,6 +125,7 @@ jobs: path: push/ - name: Build the Docker image + if: github.repository == 'OpenBankProject/OBP-API' run: | echo "${{ secrets.DOCKER_HUB_TOKEN }}" | docker login -u "${{ secrets.DOCKER_HUB_USERNAME }}" --password-stdin docker.io docker build . --file .github/Dockerfile_PreBuild --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:$GITHUB_SHA --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:${GITHUB_REF##*/} @@ -94,12 +133,14 @@ jobs: docker push docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }} --all-tags echo docker done - - uses: sigstore/cosign-installer@main + - uses: sigstore/cosign-installer@4d14d7f17e7112af04ea6108fbb4bfc714c00390 - name: Write signing key to disk (only needed for `cosign sign --key`) + if: github.repository == 'OpenBankProject/OBP-API' run: echo "${{ secrets.COSIGN_PRIVATE_KEY }}" > cosign.key - name: Sign container image + if: github.repository == 'OpenBankProject/OBP-API' run: | cosign sign -y --key cosign.key \ docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:${GITHUB_REF##*/} @@ -108,7 +149,4 @@ jobs: cosign sign -y --key cosign.key \ docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:$GITHUB_SHA env: - COSIGN_PASSWORD: "${{secrets.COSIGN_PASSWORD}}" - - - + COSIGN_PASSWORD: "${{secrets.COSIGN_PASSWORD}}" \ No newline at end of file diff --git a/.github/workflows/build_pull_request.yml b/.github/workflows/build_pull_request.yml index 859d309ec2..425177f0cb 100644 --- a/.github/workflows/build_pull_request.yml +++ b/.github/workflows/build_pull_request.yml @@ -3,15 +3,15 @@ name: Build on Pull Request on: pull_request: branches: - - '**' + - "**" env: ## Sets environment variable DOCKER_HUB_ORGANIZATION: ${{ vars.DOCKER_HUB_ORGANIZATION }} - jobs: build: runs-on: ubuntu-latest + if: github.repository == 'OpenBankProject/OBP-API' services: # Label used to access the service container redis: @@ -31,11 +31,12 @@ jobs: - name: Set up JDK 11 uses: actions/setup-java@v4 with: - java-version: '11' - distribution: 'adopt' + java-version: "11" + distribution: "adopt" cache: maven - name: Build with Maven run: | + set -o pipefail cp obp-api/src/main/resources/props/sample.props.template obp-api/src/main/resources/props/production.default.props echo connector=star > obp-api/src/main/resources/props/test.default.props echo starConnector_supported_types=mapped,internal >> obp-api/src/main/resources/props/test.default.props @@ -65,14 +66,50 @@ jobs: echo COUNTERPARTY_OTP_INSTRUCTION_TRANSPORT=dummy >> obp-api/src/main/resources/props/test.default.props echo SEPA_CREDIT_TRANSFERS_OTP_INSTRUCTION_TRANSPORT=dummy >> obp-api/src/main/resources/props/test.default.props - echo allow_oauth2_login=true >> obp-api/src/main/resources/props/test.default.props echo oauth2.jwk_set.url=https://www.googleapis.com/oauth2/v3/certs >> obp-api/src/main/resources/props/test.default.props echo ResetPasswordUrlEnabled=true >> obp-api/src/main/resources/props/test.default.props echo consents.allowed=true >> obp-api/src/main/resources/props/test.default.props - MAVEN_OPTS="-Xmx3G -Xss2m" mvn clean package -Pprod + MAVEN_OPTS="-Xmx3G -Xss2m" mvn clean package -Pprod 2>&1 | tee maven-build.log + + - name: Report failing tests (if any) + if: always() + run: | + echo "Checking build log for failing tests via grep..." + if [ ! -f maven-build.log ]; then + echo "No maven-build.log found; skipping failure scan." + exit 0 + fi + if grep -n "\*\*\* FAILED \*\*\*" maven-build.log; then + echo "Failing tests detected above." + exit 1 + else + echo "No failing tests detected in maven-build.log." + fi + + - name: Upload Maven build log + if: always() + uses: actions/upload-artifact@v4 + with: + name: maven-build-log + if-no-files-found: ignore + path: | + maven-build.log + + - name: Upload test reports + if: always() + uses: actions/upload-artifact@v4 + with: + name: test-reports + if-no-files-found: ignore + path: | + obp-api/target/surefire-reports/** + obp-commons/target/surefire-reports/** + **/target/scalatest-reports/** + **/target/site/surefire-report.html + **/target/site/surefire-report/* - name: Save .war artifact run: | @@ -81,7 +118,4 @@ jobs: - uses: actions/upload-artifact@v4 with: name: ${{ github.sha }} - path: pull/ - - - + path: pull/ \ No newline at end of file diff --git a/.github/workflows/run_trivy.yml b/.github/workflows/run_trivy.yml index 4636bd3116..e06a801f93 100644 --- a/.github/workflows/run_trivy.yml +++ b/.github/workflows/run_trivy.yml @@ -12,11 +12,10 @@ env: DOCKER_HUB_ORGANIZATION: ${{ vars.DOCKER_HUB_ORGANIZATION }} DOCKER_HUB_REPOSITORY: obp-api - jobs: build: runs-on: ubuntu-latest - if: ${{ github.event.workflow_run.conclusion == 'success' }} + if: github.repository == 'OpenBankProject/OBP-API' && github.event.workflow_run.conclusion == 'success' steps: - uses: actions/checkout@v4 @@ -38,17 +37,17 @@ jobs: - name: Run Trivy vulnerability scanner uses: aquasecurity/trivy-action@master with: - image-ref: 'docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:${{ github.sha }}' - format: 'template' - template: '@/contrib/sarif.tpl' - output: 'trivy-results.sarif' - security-checks: 'vuln' - severity: 'CRITICAL,HIGH' - timeout: '30m' + image-ref: "docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:${{ github.sha }}" + format: "template" + template: "@/contrib/sarif.tpl" + output: "trivy-results.sarif" + security-checks: "vuln" + severity: "CRITICAL,HIGH" + timeout: "30m" cache-dir: .trivy - name: Fix .trivy permissions run: sudo chown -R $(stat . -c %u:%g) .trivy - name: Upload Trivy scan results to GitHub Security tab uses: github/codeql-action/upload-sarif@v3 with: - sarif_file: 'trivy-results.sarif' \ No newline at end of file + sarif_file: "trivy-results.sarif" \ No newline at end of file