diff --git a/.github/scripts/pr-builder-7.sh b/.github/scripts/pr-builder-7.sh deleted file mode 100644 index e86d98d96be..00000000000 --- a/.github/scripts/pr-builder-7.sh +++ /dev/null @@ -1,371 +0,0 @@ -#!/bin/bash +x -OUTBOUND_AUTH_OIDC_REPO=identity-outbound-auth-oidc -OUTBOUND_AUTH_OIDC_REPO_CLONE_LINK=https://github.com/wso2-extensions/identity-outbound-auth-oidc.git -SCIM2_REPO=identity-inbound-provisioning-scim2 -SCIM2_REPO_CLONE_LINK=https://github.com/wso2-extensions/identity-inbound-provisioning-scim2.git - -echo "" -echo "==========================================================" -PR_LINK=${PR_LINK%/} -JDK_VERSION=${JDK_VERSION%/} -JAVA_8_HOME=${JAVA_8_HOME%/} -JAVA_11_HOME=${JAVA_11_HOME%/} -echo " PR_LINK: $PR_LINK" -echo " JAVA 8 Home: $JAVA_8_HOME" -echo " JAVA 11 Home: $JAVA_11_HOME" -echo " User Input: $JDK_VERSION" -echo "::warning::Build ran for PR $PR_LINK" - -USER=$(echo $PR_LINK | awk -F'/' '{print $4}') -REPO=$(echo $PR_LINK | awk -F'/' '{print $5}') -PULL_NUMBER=$(echo $PR_LINK | awk -F'/' '{print $7}') - -echo " USER: $USER" -echo " REPO: $REPO" -echo " PULL_NUMBER: $PULL_NUMBER" -echo "::set-output name=REPO_NAME::$REPO" -echo "==========================================================" -echo "Cloning product-is" -echo "==========================================================" - -git clone https://github.com/wso2/product-is - -if [ "$REPO" = "product-is" ]; then - - echo "" - echo "PR is for the product-is itself. Start building with test..." - echo "==========================================================" - cd product-is - git checkout 7.x.x - - echo "" - echo "Applying PR $PULL_NUMBER as a diff..." - echo "==========================================================" - wget -q --output-document=diff.diff $PR_LINK.diff - cat diff.diff - echo "==========================================================" - git apply diff.diff || { - echo 'Applying diff failed. Exiting...' - echo "::error::Applying diff failed." - exit 1 - } - - echo "Last 3 changes:" - COMMIT1=$(git log --oneline -1) - COMMIT2=$(git log --oneline -2 | tail -1) - COMMIT3=$(git log --oneline -3 | tail -1) - echo "$COMMIT1" - echo "$COMMIT2" - echo "$COMMIT3" - - cat pom.xml - export JAVA_HOME=$JAVA_11_HOME - mvn clean install --batch-mode | tee mvn-build.log - - PR_BUILD_STATUS=$(cat mvn-build.log | grep "\[INFO\] BUILD" | grep -oE '[^ ]+$') - PR_TEST_RESULT=$(sed -n -e '/\[INFO\] Results:/,/\[INFO\] Tests run:/ p' mvn-build.log) - - PR_BUILD_FINAL_RESULT=$( - echo "===========================================================" - echo "product-is BUILD $PR_BUILD_STATUS" - echo "==========================================================" - echo "" - echo "$PR_TEST_RESULT" - ) - - PR_BUILD_RESULT_LOG_TEMP=$(echo "$PR_BUILD_FINAL_RESULT" | sed 's/$/%0A/') - PR_BUILD_RESULT_LOG=$(echo $PR_BUILD_RESULT_LOG_TEMP) - echo "::warning::$PR_BUILD_RESULT_LOG" - - PR_BUILD_SUCCESS_COUNT=$(grep -o -i "\[INFO\] BUILD SUCCESS" mvn-build.log | wc -l) - if [ "$PR_BUILD_SUCCESS_COUNT" != "1" ]; then - echo "PR BUILD not successfull. Aborting." - echo "::error::PR BUILD not successfull. Check artifacts for logs." - exit 1 - fi -else - echo "" - echo "PR is for the dependency repository $REPO." - echo "" - echo "Cloning $USER/$REPO" - echo "==========================================================" - git clone https://github.com/$USER/$REPO - echo "" - echo "Determining dependency version property key..." - echo "==========================================================" - wget https://raw.githubusercontent.com/wso2/product-is/master/.github/scripts/version_property_finder.py - VERSION_PROPERTY=$(python version_property_finder.py $REPO product-is 2>&1) - VERSION_PROPERTY_KEY="" - if [ "$VERSION_PROPERTY" != "invalid" ]; then - echo "Version property key for the $REPO is $VERSION_PROPERTY" - VERSION_PROPERTY_KEY=$VERSION_PROPERTY - else - echo "" - echo "==========================================================" - echo "$REPO is not yet supported! Exiting..." - echo "==========================================================" - echo "" - echo "::error::PR builder not supprted" - exit 1 - fi - - echo "" - echo "Property key found: $VERSION_PROPERTY_KEY" - cd $REPO - if [ "$REPO" = "carbon-kernel" ]; then - echo "" - echo "Checking out for 4.10.x branch..." - echo "==========================================================" - git checkout 4.10.x - elif [ "$REPO" = "carbon-deployment" ]; then - echo "" - echo "Checking out for 4.x.x branch in carbon-deployment..." - echo "==========================================================" - git checkout 4.x.x - elif [ "$REPO" = "carbon-analytics-common" ]; then - echo "" - echo "Checking out for 5.2.x branch in carbon-analytics-common..." - echo "==========================================================" - git checkout 5.2.x - elif [ "$REPO" = "carbon-identity-framework" ]; then - echo "" - echo "Checking out for 6.0.x branch in carbon-identity-framework..." - echo "==========================================================" - git checkout 6.0.x - elif [ "$REPO" = "identity-governance" ]; then - echo "" - echo "Checking out for 2.0.x branch in identity-governance..." - echo "==========================================================" - git checkout 2.0.x - fi - DEPENDENCY_VERSION=$(mvn -q -Dexec.executable=echo -Dexec.args='${project.version}' --non-recursive exec:exec) - echo "Dependency Version: $DEPENDENCY_VERSION" - echo "" - echo "Applying PR $PULL_NUMBER as a diff..." - echo "==========================================================" - wget -q --output-document=diff.diff $PR_LINK.diff - cat diff.diff - echo "==========================================================" - git apply diff.diff || { - echo 'Applying diff failed. Exiting...' - echo "::error::Applying diff failed." - exit 1 - } - - echo "" - echo "Building dependency repo $REPO..." - echo "==========================================================" - - if [ "$JDK_VERSION" = "11" ]; then - export JAVA_HOME=$JAVA_11_HOME - else - export JAVA_HOME=$JAVA_8_HOME - fi - - if [ "$REPO" = "carbon-kernel" ]; then - mvn clean install -Dmaven.test.skip=true --batch-mode | tee mvn-build.log - else - mvn clean install --batch-mode | tee mvn-build.log - fi - - echo "" - echo "Dependency repo $REPO build complete." - echo "Built version: $DEPENDENCY_VERSION" - echo "==========================================================" - echo "" - - REPO_BUILD_STATUS=$(cat mvn-build.log | grep "\[INFO\] BUILD" | grep -oE '[^ ]+$') - REPO_TEST_RESULT_1=$(sed -n -e '/Results :/,/Tests run:/ p' mvn-build.log) - REPO_TEST_RESULT_2=$(sed -n -e '/\[INFO\] Results:/,/\[INFO\] Tests run:/ p' mvn-build.log) - - REPO_FINAL_RESULT=$( - echo "===========================================================" - echo "$REPO BUILD $REPO_BUILD_STATUS" - echo "==========================================================" - echo "" - echo "Built version: $DEPENDENCY_VERSION" - echo "" - echo "$REPO_TEST_RESULT_1" - echo "" - echo "$REPO_TEST_RESULT_2" - ) - - REPO_BUILD_RESULT_LOG_TEMP=$(echo "$REPO_FINAL_RESULT" | sed 's/$/%0A/') - REPO_BUILD_RESULT_LOG=$(echo $REPO_BUILD_RESULT_LOG_TEMP) - echo "::warning::$REPO_BUILD_RESULT_LOG" - - if [ "$REPO_BUILD_STATUS" != "SUCCESS" ]; then - echo "$REPO BUILD not successfull. Aborting." - echo "::error::$REPO BUILD not successfull. Check artifacts for logs." - exit 1 - fi - cd .. - - OUTBOUND_AUTH_OIDC_VERSION_PROPERTY_KEY="" - OUTBOUND_AUTH_OIDC_DEPENDENCY_VERSION="" - if [ "$REPO" = "carbon-kernel" ]; then - echo "" - echo "Building Outbound Auth OIDC repo..." - echo "==========================================================" - git clone $OUTBOUND_AUTH_OIDC_REPO_CLONE_LINK - OUTBOUND_AUTH_OIDC_VERSION_PROPERTY=$(python version_property_finder.py $OUTBOUND_AUTH_OIDC_REPO product-is 2>&1) - if [ "$OUTBOUND_AUTH_OIDC_VERSION_PROPERTY" != "invalid" ]; then - echo "Version property key for the $OUTBOUND_AUTH_OIDC_REPO is $OUTBOUND_AUTH_OIDC_VERSION_PROPERTY" - OUTBOUND_AUTH_OIDC_VERSION_PROPERTY_KEY=$OUTBOUND_AUTH_OIDC_VERSION_PROPERTY - else - echo "" - echo "==========================================================" - echo "Unable to find the version property for $OUTBOUND_AUTH_OIDC_REPO..." - echo "==========================================================" - echo "" - echo "::error::Unable to find the version property for $OUTBOUND_AUTH_OIDC_REPO..." - exit 1 - fi - cd $OUTBOUND_AUTH_OIDC_REPO - OUTBOUND_AUTH_OIDC_DEPENDENCY_VERSION=$(mvn -q -Dexec.executable=echo -Dexec.args='${project.version}' --non-recursive exec:exec) - echo "Outbound Auth OIDC Dependency Version: $OUTBOUND_AUTH_OIDC_DEPENDENCY_VERSION" - echo "" - - KERNEL_VERSION_PROPERTY_KEY=carbon.kernel.version - echo "Updating carbon-kernel dependency version in identity-outbound-auth-oidc repo..." - echo "==========================================================" - echo "" - sed -i "s/<$KERNEL_VERSION_PROPERTY_KEY>.*<\/$KERNEL_VERSION_PROPERTY_KEY>/<$KERNEL_VERSION_PROPERTY_KEY>$DEPENDENCY_VERSION<\/$KERNEL_VERSION_PROPERTY_KEY>/" pom.xml - - echo "" - echo "Building repo $OUTBOUND_AUTH_OIDC_REPO..." - echo "==========================================================" - - - export JAVA_HOME=$JAVA_11_HOME - mvn clean install -Dmaven.test.skip=true --batch-mode | tee mvn-build.log - - echo "Repo $OUTBOUND_AUTH_OIDC_REPO build complete." - SUB_REPO_BUILD_STATUS=$(cat mvn-build.log | grep "\[INFO\] BUILD" | grep -oE '[^ ]+$') - - if [ "$SUB_REPO_BUILD_STATUS" != "SUCCESS" ]; then - echo "$OUTBOUND_AUTH_OIDC_REPO repo build not successfull. Aborting." - echo "::error::$OUTBOUND_AUTH_OIDC_REPO repo build not successfull. Aborting." - exit 1 - fi - - echo "" - echo "Built version: $OUTBOUND_AUTH_OIDC_DEPENDENCY_VERSION" - echo "==========================================================" - echo "" - cd .. - fi - - SCIM2_VERSION_PROPERTY_KEY="" - SCIM2_DEPENDENCY_VERSION="" - if [ "$REPO" = "charon" ]; then - echo "" - echo "Building SCIM2 repo..." - echo "==========================================================" - git clone $SCIM2_REPO_CLONE_LINK - SCIM2_VERSION_PROPERTY=$(python version_property_finder.py $SCIM2_REPO product-is 2>&1) - if [ "$SCIM2_VERSION_PROPERTY" != "invalid" ]; then - echo "Version property key for the $SCIM2_REPO is $SCIM2_VERSION_PROPERTY" - SCIM2_VERSION_PROPERTY_KEY=$SCIM2_VERSION_PROPERTY - else - echo "" - echo "==========================================================" - echo "Unable to find the version property for $SCIM2_REPO..." - echo "==========================================================" - echo "" - echo "::error::Unable to find the version property for $SCIM2_REPO..." - exit 1 - fi - cd $SCIM2_REPO - SCIM2_DEPENDENCY_VERSION=$(mvn -q -Dexec.executable=echo -Dexec.args='${project.version}' --non-recursive exec:exec) - echo "SCIM2 Dependency Version: $SCIM2_DEPENDENCY_VERSION" - echo "" - - CHARON_VERSION_PROPERTY_KEY=charon.version - echo "Updating charon dependency version in $SCIM2_REPO repo..." - echo "==========================================================" - echo "" - sed -i "s/<$CHARON_VERSION_PROPERTY_KEY>.*<\/$CHARON_VERSION_PROPERTY_KEY>/<$CHARON_VERSION_PROPERTY_KEY>$DEPENDENCY_VERSION<\/$CHARON_VERSION_PROPERTY_KEY>/" pom.xml - - echo "" - echo "Building $SCIM2_REPO repo..." - echo "==========================================================" - - export JAVA_HOME=$JAVA_8_HOME - mvn clean install -Dmaven.test.skip=true --batch-mode | tee mvn-build.log - - echo "Repo $SCIM2_REPO build complete." - SUB_REPO_BUILD_STATUS=$(cat mvn-build.log | grep "\[INFO\] BUILD" | grep -oE '[^ ]+$') - - if [ "$SUB_REPO_BUILD_STATUS" != "SUCCESS" ]; then - echo "$SCIM2_REPO repo build not successfull. Aborting." - echo "::error::$SCIM2_REPO repo build not successfull. Aborting." - exit 1 - fi - - echo "" - echo "Built version: $SCIM2_DEPENDENCY_VERSION" - echo "==========================================================" - echo "" - cd .. - fi - - cd product-is - git checkout 7.x.x - - echo "Updating dependency version in product-is..." - echo "==========================================================" - echo "" - if [ "$REPO" = "charon" ]; then - echo "Updating SCIM2 version in product-is..." - echo "==========================================================" - echo "" - sed -i "s/<$SCIM2_VERSION_PROPERTY_KEY>.*<\/$SCIM2_VERSION_PROPERTY_KEY>/<$SCIM2_VERSION_PROPERTY_KEY>$SCIM2_DEPENDENCY_VERSION<\/$SCIM2_VERSION_PROPERTY_KEY>/" pom.xml - else - sed -i "s/<$VERSION_PROPERTY_KEY>.*<\/$VERSION_PROPERTY_KEY>/<$VERSION_PROPERTY_KEY>$DEPENDENCY_VERSION<\/$VERSION_PROPERTY_KEY>/" pom.xml - if [ "$REPO" = "carbon-kernel" ]; then - echo "Updating Outbound Auth OIDC version in product-is..." - echo "==========================================================" - echo "" - sed -i "s/<$OUTBOUND_AUTH_OIDC_VERSION_PROPERTY_KEY>.*<\/$OUTBOUND_AUTH_OIDC_VERSION_PROPERTY_KEY>/<$OUTBOUND_AUTH_OIDC_VERSION_PROPERTY_KEY>$OUTBOUND_AUTH_OIDC_DEPENDENCY_VERSION<\/$OUTBOUND_AUTH_OIDC_VERSION_PROPERTY_KEY>/" pom.xml - echo "Updating caron-kernel version in carbon.product..." - echo "==========================================================" - echo "" - KERNEL_DEPENDENCY_VERSION=$(echo $DEPENDENCY_VERSION | sed -e "s/-/./g") - echo "Dependency version for carbon.product : $KERNEL_DEPENDENCY_VERSION" - sed -i "s/version=\"4.10.*\"/version=\"$KERNEL_DEPENDENCY_VERSION\"/g" modules/p2-profile-gen/carbon.product - fi - fi - - export JAVA_HOME=$JAVA_11_HOME - cat pom.xml - mvn clean install --batch-mode | tee mvn-build.log - - PR_BUILD_STATUS=$(cat mvn-build.log | grep "\[INFO\] BUILD" | grep -oE '[^ ]+$') - PR_TEST_RESULT=$(sed -n -e '/\[INFO\] Results:/,/\[INFO\] Tests run:/ p' mvn-build.log) - - PR_BUILD_FINAL_RESULT=$( - echo "===========================================================" - echo "product-is BUILD $PR_BUILD_STATUS" - echo "==========================================================" - echo "" - echo "$PR_TEST_RESULT" - ) - - PR_BUILD_RESULT_LOG_TEMP=$(echo "$PR_BUILD_FINAL_RESULT" | sed 's/$/%0A/') - PR_BUILD_RESULT_LOG=$(echo $PR_BUILD_RESULT_LOG_TEMP) - echo "::warning::$PR_BUILD_RESULT_LOG" - - PR_BUILD_SUCCESS_COUNT=$(grep -o -i "\[INFO\] BUILD SUCCESS" mvn-build.log | wc -l) - if [ "$PR_BUILD_SUCCESS_COUNT" != "1" ]; then - echo "PR BUILD not successfull. Aborting." - echo "::error::PR BUILD not successfull. Check artifacts for logs." - exit 1 - fi -fi - -echo "" -echo "==========================================================" -echo "Build completed" -echo "==========================================================" -echo "" diff --git a/.github/scripts/pr-builder.sh b/.github/scripts/pr-builder.sh index 83c681ef493..c191e75a666 100644 --- a/.github/scripts/pr-builder.sh +++ b/.github/scripts/pr-builder.sh @@ -23,7 +23,7 @@ PULL_NUMBER=$(echo $PR_LINK | awk -F'/' '{print $7}') echo " USER: $USER" echo " REPO: $REPO" echo " PULL_NUMBER: $PULL_NUMBER" -echo "::set-output name=REPO_NAME::$REPO" +echo "REPO_NAME=$REPO" >> "$GITHUB_OUTPUT" echo "==========================================================" echo "Cloning product-is" echo "==========================================================" diff --git a/.github/workflows/dependency-updater-7.yml b/.github/workflows/dependency-updater-7.yml deleted file mode 100644 index 6989aeeef74..00000000000 --- a/.github/workflows/dependency-updater-7.yml +++ /dev/null @@ -1,161 +0,0 @@ -# This workflow will update dependencies for product-is 7.x.x. -name: "[Deprecated] Dependency Updater 7.x.x" -on: - workflow_dispatch: - # schedule: - # Everyday at 15:30 UTC (9.00 PM SL time) - # - cron: '30 15 * * *' - -env: - MAVEN_OPTS: -Xmx4g -Xms1g - REPOSITORY: product-is - GIT_USERNAME: jenkins-is-staging - GIT_EMAIL: jenkins-is-staging@wso2.com - PRODUCT_REPOSITORY_FORKED: $GIT_USERNAME'/'${REPOSITORY} - REMOTE_PRODUCT_REPOSITORY_PUBLIC: wso2/$REPOSITORY - PRODUCT_REPOSITORY_PUBLIC: wso2/$REPOSITORY - BUILD_NUMBER: ${{github.run_id}} - DEPENDENCY_UPGRADE_BRANCH_NAME: IS_dependency_updater_7.x.x_github_action/$BUILD_NUMBER - PR: "https://github.com/wso2/product-is/pulls" - TARGET_BRANCH_NAME: 7.x.x - -jobs: - build: - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v2 - - name: Set up Adopt JDK 11 - uses: actions/setup-java@v2 - with: - java-version: "11" - distribution: "adopt" - - name: Check $JAVA_HOME - run: | - echo $JAVA_HOME - - name: Cache local Maven repository - id: cache-maven-m2 - uses: actions/cache@v2 - env: - cache-name: cache-m2 - with: - path: ~/.m2/repository - key: ${{ runner.os }}-maven-${{ env.cache-name }}-${{ hashFiles('**/pom.xml') }} - restore-keys: | - ${{ runner.os }}-maven-${{ env.cache-name }}- - ${{ runner.os }}-maven- - ${{ runner.os }}- - - name: Update Dependencies - id: builder_step - run: | - echo "::set-output name=REPO_NAME::${{ env.REPOSITORY }}" - echo "" - echo "Starting dependency upgrade" - echo "==========================================================" - echo "" - echo "Clean up any existing files" - echo "==========================================================" - rm -rf ${{ env.REPOSITORY }} - echo "" - echo "Cloning: https://github.com/'${{ env.PRODUCT_REPOSITORY_FORKED }}" - echo "==========================================================" - git clone 'https://github.com/'${{ env.PRODUCT_REPOSITORY_FORKED }}'.git' - cd ${{ env.REPOSITORY }} - echo "" - echo 'Add remote: '${{ env.REMOTE_PRODUCT_REPOSITORY_PUBLIC }} 'as https://github.com/'${{ env.PRODUCT_REPOSITORY_PUBLIC }} - echo "==========================================================" - git remote add ${{ env.REMOTE_PRODUCT_REPOSITORY_PUBLIC }} 'https://@github.com/'${{ env.PRODUCT_REPOSITORY_PUBLIC }} - echo "" - echo 'Fetching:' ${{ env.REMOTE_PRODUCT_REPOSITORY_PUBLIC }} - echo "==========================================================" - git fetch ${{ env.REMOTE_PRODUCT_REPOSITORY_PUBLIC }} - echo "" - echo 'Checking out:' ${{ env.REMOTE_PRODUCT_REPOSITORY_PUBLIC }} ${{ env.TARGET_BRANCH_NAME }} 'branch' - echo "==========================================================" - git checkout -b ${{ env.DEPENDENCY_UPGRADE_BRANCH_NAME }} ${{ env.REMOTE_PRODUCT_REPOSITORY_PUBLIC }}'/'${{ env.TARGET_BRANCH_NAME }} - - echo "" - echo 'Updating dependencies' - echo "==========================================================" - mvn versions:update-properties -U -DgenerateBackupPoms=false -DallowMajorUpdates=false -Dincludes=org.wso2.carbon.identity.*,org.wso2.carbon.extension.identity.*,org.wso2.identity.*,org.wso2.carbon.consent.*,org.wso2.carbon.healthcheck.*,org.wso2.carbon.utils,org.wso2.charon,org.apache.rampart.wso2,org.apache.ws.security.wso2 - echo "" - echo 'Available updates' - echo "==========================================================" - git diff --color > dependency_updates.diff - cat dependency_updates.diff - - echo "" - echo 'Build' - echo "==========================================================" - mvn clean install -Dmaven.test.failure.ignore=false | tee mvn-build.log - PR_BUILD_STATUS=$(cat mvn-build.log | grep "\[INFO\] BUILD" | grep -oE '[^ ]+$') - PR_TEST_RESULT=$(sed -n -e '/\[INFO\] Results:/,/\[INFO\] Tests run:/ p' mvn-build.log) - PR_BUILD_FINAL_RESULT=$( - echo "===========================================================" - echo "product-is BUILD $PR_BUILD_STATUS" - echo "==========================================================" - echo "" - echo "$PR_TEST_RESULT" - ) - PR_BUILD_RESULT_LOG_TEMP=$(echo "$PR_BUILD_FINAL_RESULT" | sed 's/$/%0A/') - PR_BUILD_RESULT_LOG=$(echo $PR_BUILD_RESULT_LOG_TEMP) - echo "::warning::$PR_BUILD_RESULT_LOG" - PR_BUILD_SUCCESS_COUNT=$(grep -o -i "\[INFO\] BUILD SUCCESS" mvn-build.log | wc -l) - if [ "$PR_BUILD_SUCCESS_COUNT" != "1" ]; then - echo "PR BUILD not successfull. Aborting." - echo "::error::PR BUILD not successfull. Check artifacts for logs." - exit 1 - fi - - if [ -s dependency_updates.diff ] - then - echo "" - echo 'Commit Changes' - echo "==========================================================" - git config --global user.email ${{ env.GIT_EMAIL }} - git config --global user.name ${{ env.GIT_USERNAME }} - git commit -a -m 'Bump dependencies from '${{ env.DEPENDENCY_UPGRADE_BRANCH_NAME }} - git remote rm origin - git remote add origin 'https://'${{ secrets.PAT }}'@github.com/'${{ env.PRODUCT_REPOSITORY_FORKED }} - - echo "" - echo 'Push Changes' - echo "==========================================================" - git push -u origin ${{ env.DEPENDENCY_UPGRADE_BRANCH_NAME }} - - echo "" - echo 'Send Pull Request' - echo "==========================================================" - - TITLE="[7.x.x] Bump Dependencies #"${{ env.BUILD_NUMBER }} - RESPONSE=$(curl -s -w "%{http_code}" -k -X \ - POST https://api.github.com/repos/${{ env.PRODUCT_REPOSITORY_PUBLIC }}/pulls \ - -H "Authorization: Bearer "${{ secrets.PAT }}"" \ - -H "Content-Type: application/json" \ - -d '{ "title": "'"${TITLE}"'","body": "Bumps dependencies for product-is. Link : https://github.com/wso2/product-is/actions/runs/${{github.run_id}}","head": "'"${{ env.GIT_USERNAME }}:${{ env.DEPENDENCY_UPGRADE_BRANCH_NAME }}"'","base":"'"${{ env.TARGET_BRANCH_NAME }}"'"}') - RESPONSE_BODY=${RESPONSE::-3} - STATUS=$(printf "%s" "$RESPONSE" | tail -c 3) - if [[ $STATUS == "201" ]]; then - echo "PR=$(echo $RESPONSE_BODY | jq -r '.html_url')" >> $GITHUB_ENV - fi - else - echo "" - echo "There are no dependency updates available" - echo "==========================================================" - exit 0 - fi - - name: Archive dependency diff file - if: always() - uses: actions/upload-artifact@v4 - with: - name: dependency-updates-diff - path: | - ${{steps.builder_step.outputs.REPO_NAME}}/dependency_updates.diff - - name: Archive maven-build-log file - if: always() - uses: actions/upload-artifact@v4 - with: - name: mvn-build.log - path: | - ${{steps.builder_step.outputs.REPO_NAME}}/mvn-build.log - if-no-files-found: warn diff --git a/.github/workflows/dependency-updater.yml b/.github/workflows/dependency-updater.yml index 284ac65fe0a..c12d9c1e4cc 100644 --- a/.github/workflows/dependency-updater.yml +++ b/.github/workflows/dependency-updater.yml @@ -7,7 +7,7 @@ on: - cron: '0 15 * * *' env: - MAVEN_OPTS: -Xmx4g -Xms1g + MAVEN_OPTS: -Xmx4g -Xms1g -XX:+HeapDumpOnOutOfMemoryError REPOSITORY: product-is GIT_USERNAME: jenkins-is-staging GIT_EMAIL: jenkins-is-staging@wso2.com @@ -26,9 +26,9 @@ jobs: JAVA_TOOL_OPTIONS: "-Djdk.util.zip.disableZip64ExtraFieldValidation=true -Djdk.nio.zipfs.allowDotZipEntry=true" steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 - name: Set up Adopt JDK 11 - uses: actions/setup-java@v2 + uses: actions/setup-java@v4 with: java-version: "11" distribution: "adopt" @@ -37,7 +37,7 @@ jobs: echo $JAVA_HOME - name: Cache local Maven repository id: cache-maven-m2 - uses: actions/cache@v2 + uses: actions/cache@v4 env: cache-name: cache-m2 with: @@ -50,7 +50,7 @@ jobs: - name: Update Dependencies id: builder_step run: | - echo "::set-output name=REPO_NAME::${{ env.REPOSITORY }}" + echo "REPO_NAME=${{ env.REPOSITORY }}" >> "$GITHUB_OUTPUT" echo "" echo "Starting dependency upgrade" echo "==========================================================" @@ -161,6 +161,14 @@ jobs: path: | ${{steps.builder_step.outputs.REPO_NAME}}/mvn-build.log if-no-files-found: warn + - name: Archive heap dump + if: always() + uses: actions/upload-artifact@v4 + with: + name: heap-dump + path: | + **/**.hprof + if-no-files-found: ignore - name: Google Chat Notification run: | STATUS_COLOR=$(if [[ ${{ job.status }} == "success" ]];then echo "#009944"; diff --git a/.github/workflows/fapi-oidc-conformance-test.yml b/.github/workflows/fapi-oidc-conformance-test.yml index db67cf415cd..36829d3aec2 100644 --- a/.github/workflows/fapi-oidc-conformance-test.yml +++ b/.github/workflows/fapi-oidc-conformance-test.yml @@ -32,14 +32,15 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: path: './product-is' - name: Set up JDK 11 - uses: actions/setup-java@v1 + uses: actions/setup-java@v4 with: java-version: 11.0.18+10 + distribution: temurin - name: Setup Python run: | @@ -189,7 +190,7 @@ jobs: python3 ./configure_is_fapi.py ../../$PRODUCT_IS_ZIP - name: Set up JDK 17 - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: java-version: 17 distribution: temurin diff --git a/.github/workflows/fork-branch-deleter.yml b/.github/workflows/fork-branch-deleter.yml index a6b1e897c69..d6dbcb6c902 100644 --- a/.github/workflows/fork-branch-deleter.yml +++ b/.github/workflows/fork-branch-deleter.yml @@ -13,7 +13,7 @@ jobs: steps: # Check out the product-is fork of 'jenkins-is-staging' user - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 with: repository: ${{ github.event.pull_request.head.repo.full_name }} token: ${{ secrets.PAT }} diff --git a/.github/workflows/fossa-scanner.yaml b/.github/workflows/fossa-scanner.yaml index f735365f733..b735f753f62 100644 --- a/.github/workflows/fossa-scanner.yaml +++ b/.github/workflows/fossa-scanner.yaml @@ -8,7 +8,7 @@ jobs: fossa-scan: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - uses: fossas/fossa-action@main with: api-key: ${{secrets.FOSSAAPIKEY}} diff --git a/.github/workflows/migration-automation.yml b/.github/workflows/migration-automation.yml index eead65a5089..b4d9167c57d 100644 --- a/.github/workflows/migration-automation.yml +++ b/.github/workflows/migration-automation.yml @@ -53,7 +53,7 @@ jobs: runs-on: ${{ github.event.inputs.os }} steps: - name: Checkout code - uses: actions/checkout@v2 + uses: actions/checkout@v4 - name: Setup Docker environment run: | # Get the ID of the workflow from the GitHub API using curl and jq @@ -136,7 +136,7 @@ jobs: runs-on: ${{ github.event.inputs.os }} steps: - name: Checkout code - uses: actions/checkout@v2 + uses: actions/checkout@v4 - name: Execute Migration Automation Script Ubuntu run: | chmod +x ${{ github.workspace }}/.github/migration-tester/migration-automation/ubuntu-os/migration-script-ubuntu.sh @@ -172,7 +172,7 @@ jobs: steps: - name: Checkout code - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Create MS SQL Database run: | @@ -215,7 +215,7 @@ jobs: runs-on: ${{ github.event.inputs.os }} steps: - name: Checkout code - uses: actions/checkout@v2 + uses: actions/checkout@v4 - name: Execute Migration Automation Script Mac run: | @@ -240,7 +240,7 @@ jobs: if: ${{ github.event.inputs.database == 'postgres' && github.event.inputs.os == 'macos-latest' }} steps: - name: Checkout code - uses: actions/checkout@v2 + uses: actions/checkout@v4 - name: Set up PostgreSQL env: PGDATA: /usr/local/var/postgres @@ -287,7 +287,7 @@ jobs: runs-on: ${{ github.event.inputs.os }} steps: - name: Checkout code - uses: actions/checkout@v2 + uses: actions/checkout@v4 - uses: potatoqualitee/mssqlsuite@v1.7 with: @@ -344,7 +344,7 @@ jobs: runs-on: ${{ github.event.inputs.os }} steps: - name: Checkout code - uses: actions/checkout@v2 + uses: actions/checkout@v4 - name: Download Artifacts uses: actions/download-artifact@v2 if: always() diff --git a/.github/workflows/oidc-conformance-test.yml b/.github/workflows/oidc-conformance-test.yml index e6391ced686..bd4d328dbfa 100644 --- a/.github/workflows/oidc-conformance-test.yml +++ b/.github/workflows/oidc-conformance-test.yml @@ -36,14 +36,15 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: path: './product-is' - name: Set up JDK 11 - uses: actions/setup-java@v1 + uses: actions/setup-java@v4 with: java-version: 11.0.18+10 + distribution: temurin - name: Setup Python run: | @@ -142,7 +143,7 @@ jobs: python3 ./configure_is.py ../../$PRODUCT_IS_ZIP $ROOT_DIR $ROOT_DIR/jacoco.exec - name: Set up JDK 17 - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: java-version: 17 distribution: temurin diff --git a/.github/workflows/pr-builder-test-JDK11-7.yml b/.github/workflows/pr-builder-test-JDK11-7.yml deleted file mode 100644 index 75aab52ac5c..00000000000 --- a/.github/workflows/pr-builder-test-JDK11-7.yml +++ /dev/null @@ -1,130 +0,0 @@ -name: "[Deprecated] pr-builder-test 7.x.x" - -on: - workflow_dispatch: - inputs: - pr: - description: "Enter PR link (ex: https://github.com/wso2-extensions/identity-inbound-auth-oauth/pull/1481)" - default: - required: true - jdk: - description: "Enter Java version (ex: 8,11)" - default: - required: true - -env: - MAVEN_OPTS: -Dhttp.keepAlive=false -Dmaven.wagon.http.pool=false -Dmaven.wagon.http.retryHandler.class=standard -Dmaven.wagon.http.retryHandler.count=3 - - -jobs: - build: - runs-on: ubuntu-latest - - steps: - - name: Print Input - run: echo Running the PR builder for PR - ${{ github.event.inputs.pr }} - - name: Comment build info - run: | - owner=$(echo '${{github.event.inputs.pr}}' | cut -d "/" -f 4) - repo=$(echo '${{github.event.inputs.pr}}' | cut -d "/" -f 5) - pr_number=$(echo '${{github.event.inputs.pr}}' | cut -d "/" -f 7) - curl -X POST https://api.github.com/repos/$owner/$repo/issues/$pr_number/comments -H 'Authorization: token ${{secrets.PR_BUILDER_COMMENT}}' -d '{"body":"PR builder [7.x.x] started \nLink: https://github.com/wso2/product-is/actions/runs/${{github.run_id}}"}' - - uses: actions/checkout@v2 - - name: Set up Adopt JDK 8 - uses: actions/setup-java@v2 - with: - java-version: "8" - distribution: "adopt" - - name: Echo java 8 home - run: | - echo "J8HOME=$JAVA_HOME" >> ${GITHUB_ENV} - id: java-8-setup - - name: Set up Adopt JDK 11 - uses: actions/setup-java@v2 - with: - java-version: "11" - distribution: "adopt" - - name: Echo java 11 home - run: | - echo "J11HOME=$JAVA_HOME" >> ${GITHUB_ENV} - - name: Build init - run: | - echo "CURRENT_MONTH=$(date +%Y-%m)" >> ${GITHUB_ENV} - - name: Cache maven packages - id: cache-maven-m2 - uses: actions/cache@v2 - with: - path: | - ~/.m2 - !~/.m2/repository/org/wso2/is/wso2is - key: ${{ runner.os }}-pr-builder-${{ env.CURRENT_MONTH }} - - name: Setup pnpm - id: setup-pnpm - uses: pnpm/action-setup@v2.1.0 - with: - version: latest - run_install: false - - name: Run PR builder - id: builder_step - env: - PR_LINK: ${{github.event.inputs.pr}} - JDK_VERSION: ${{github.event.inputs.jdk}} - JAVA_8_HOME: ${{env.J8HOME}} - JAVA_11_HOME: ${{env.J11HOME}} - run: | - wget https://raw.githubusercontent.com/wso2/product-is/master/.github/scripts/pr-builder-7.sh - bash pr-builder-7.sh - - name: Archive PR diff file - if: always() - uses: actions/upload-artifact@v4 - with: - name: repo-pr-diff - path: | - ${{steps.builder_step.outputs.REPO_NAME}}/diff.diff - if-no-files-found: warn - - name: Archive repo mvn build log - if: always() && steps.builder_step.outputs.REPO_NAME != 'product-is' - uses: actions/upload-artifact@v4 - with: - name: repo-mvn-build-log - path: | - ${{steps.builder_step.outputs.REPO_NAME}}/mvn-build.log - if-no-files-found: warn - - name: Archive repo surefire reports - if: always() && steps.builder_step.outputs.REPO_NAME != 'product-is' - uses: actions/upload-artifact@v4 - with: - name: repo-surefire-report - path: | - ${{steps.builder_step.outputs.REPO_NAME}}/**/surefire-reports - if-no-files-found: warn - - name: Archive product-is mvn build log - if: always() - uses: actions/upload-artifact@v4 - with: - name: product-is-mvn-build-log - path: | - product-is/mvn-build.log - if-no-files-found: warn - - name: Archive product-is surefire reports - if: always() - uses: actions/upload-artifact@v4 - with: - name: product-is-surefire-report - path: | - product-is/**/surefire-reports - if-no-files-found: warn - - name: Comment build status - if: always() - run: | - owner=$(echo '${{github.event.inputs.pr}}' | cut -d "/" -f 4) - repo=$(echo '${{github.event.inputs.pr}}' | cut -d "/" -f 5) - pr_number=$(echo '${{github.event.inputs.pr}}' | cut -d "/" -f 7) - curl -X POST https://api.github.com/repos/$owner/$repo/issues/$pr_number/comments -H 'Authorization: token ${{secrets.PR_BUILDER_COMMENT}}' -d '{"body":"PR builder [7.x.x] completed \nLink: https://github.com/wso2/product-is/actions/runs/${{github.run_id}} \nStatus: **${{job.status}}**"}' - - name: Approve PR - if: success() - run: | - owner=$(echo '${{github.event.inputs.pr}}' | cut -d "/" -f 4) - repo=$(echo '${{github.event.inputs.pr}}' | cut -d "/" -f 5) - pr_number=$(echo '${{github.event.inputs.pr}}' | cut -d "/" -f 7) - curl -X POST https://api.github.com/repos/$owner/$repo/pulls/$pr_number/reviews -H 'Authorization:token ${{secrets.PR_BUILDER_COMMENT}}' -d '{"body":"Approving the pull request based on the successful pr build https://github.com/wso2/product-is/actions/runs/${{github.run_id}}","event":"APPROVE"}' diff --git a/.github/workflows/pr-builder-test-JDK11.yml b/.github/workflows/pr-builder-test-JDK11.yml index 8dba76647fc..1a15290ef75 100644 --- a/.github/workflows/pr-builder-test-JDK11.yml +++ b/.github/workflows/pr-builder-test-JDK11.yml @@ -13,7 +13,7 @@ on: required: true env: - MAVEN_OPTS: -Dhttp.keepAlive=false -Dmaven.wagon.http.pool=false -Dmaven.wagon.http.retryHandler.class=standard -Dmaven.wagon.http.retryHandler.count=3 -Djdk.util.zip.disableZip64ExtraFieldValidation=true + MAVEN_OPTS: -Dhttp.keepAlive=false -Dmaven.wagon.http.pool=false -Dmaven.wagon.http.retryHandler.class=standard -Dmaven.wagon.http.retryHandler.count=3 -Djdk.util.zip.disableZip64ExtraFieldValidation=true -XX:+HeapDumpOnOutOfMemoryError jobs: @@ -32,9 +32,9 @@ jobs: repo=$(echo '${{github.event.inputs.pr}}' | cut -d "/" -f 5) pr_number=$(echo '${{github.event.inputs.pr}}' | cut -d "/" -f 7) curl -X POST https://api.github.com/repos/$owner/$repo/issues/$pr_number/comments -H 'Authorization: token ${{secrets.PR_BUILDER_COMMENT}}' -d '{"body":"PR builder started \nLink: https://github.com/wso2/product-is/actions/runs/${{github.run_id}}"}' - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 - name: Set up Adopt JDK 8 - uses: actions/setup-java@v2 + uses: actions/setup-java@v4 with: java-version: "8" distribution: "adopt" @@ -43,7 +43,7 @@ jobs: echo "J8HOME=$JAVA_HOME" >> ${GITHUB_ENV} id: java-8-setup - name: Set up Adopt JDK 11 - uses: actions/setup-java@v2 + uses: actions/setup-java@v4 with: java-version: "11" distribution: "adopt" @@ -55,7 +55,7 @@ jobs: echo "CURRENT_MONTH=$(date +%Y-%m)" >> ${GITHUB_ENV} - name: Cache maven packages id: cache-maven-m2 - uses: actions/cache@v2 + uses: actions/cache@v4 with: path: | ~/.m2 @@ -63,7 +63,7 @@ jobs: key: ${{ runner.os }}-pr-builder-${{ env.CURRENT_MONTH }} - name: Setup pnpm id: setup-pnpm - uses: pnpm/action-setup@v2.1.0 + uses: pnpm/action-setup@v4 with: version: latest run_install: false @@ -117,6 +117,14 @@ jobs: path: | product-is/**/surefire-reports if-no-files-found: warn + - name: Archive heap dump + if: always() + uses: actions/upload-artifact@v4 + with: + name: heap-dump + path: | + **/**.hprof + if-no-files-found: ignore - name: Comment build status if: always() run: | diff --git a/.github/workflows/product-is-builder-jdk17.yml b/.github/workflows/product-is-builder-jdk17.yml index c94a139c99d..5ab1355da9d 100644 --- a/.github/workflows/product-is-builder-jdk17.yml +++ b/.github/workflows/product-is-builder-jdk17.yml @@ -20,9 +20,9 @@ jobs: steps: - name: Checkout repository code - uses: actions/checkout@v2 + uses: actions/checkout@v4 - name: Set up Adopt JDK 11 - uses: actions/setup-java@v2 + uses: actions/setup-java@v4 with: java-version: "11" distribution: "adopt" @@ -30,7 +30,7 @@ jobs: run: | mvn clean install --batch-mode -Dmaven.test.skip=true | tee mvn-build.log - name: Set up Adopt JDK 17 - uses: actions/setup-java@v2 + uses: actions/setup-java@v4 with: java-version: "17" distribution: "adopt" diff --git a/.github/workflows/product-is-builder-jdk21.yml b/.github/workflows/product-is-builder-jdk21.yml index 632f0b71100..772a3331918 100644 --- a/.github/workflows/product-is-builder-jdk21.yml +++ b/.github/workflows/product-is-builder-jdk21.yml @@ -20,9 +20,9 @@ jobs: steps: - name: Checkout repository code - uses: actions/checkout@v2 + uses: actions/checkout@v4 - name: Set up Adopt JDK 11 - uses: actions/setup-java@v2 + uses: actions/setup-java@v4 with: java-version: "11" distribution: "adopt" @@ -30,7 +30,7 @@ jobs: run: | mvn clean install --batch-mode -Dmaven.test.skip=true | tee mvn-build.log - name: Set up Adopt JDK 21 - uses: actions/setup-java@v2 + uses: actions/setup-java@v4 with: java-version: "21" distribution: "adopt" diff --git a/modules/api-resources/api-resources-full/pom.xml b/modules/api-resources/api-resources-full/pom.xml index e9b975035a7..4b274403394 100644 --- a/modules/api-resources/api-resources-full/pom.xml +++ b/modules/api-resources/api-resources-full/pom.xml @@ -23,12 +23,12 @@ org.wso2.is api-resources - 7.1.0-m5-SNAPSHOT + 7.1.0-m6-SNAPSHOT ../pom.xml api-resources-full - 7.1.0-m5-SNAPSHOT + 7.1.0-m6-SNAPSHOT war WSO2 Identity Server - All Rest API @@ -440,10 +440,6 @@ org.wso2.carbon.identity.governance org.wso2.carbon.identity.api.user.governance - - org.wso2.carbon.identity.framework - org.wso2.carbon.identity.api.server.entitlement - org.wso2.carbon.identity.framework org.wso2.carbon.identity.api.server.configuration.mgt @@ -504,5 +500,13 @@ org.wso2.carbon.identity.server.api org.wso2.carbon.identity.api.server.action.management.common + + org.wso2.carbon.identity.server.api + org.wso2.carbon.identity.api.server.rule.metadata.v1 + + + org.wso2.carbon.identity.server.api + org.wso2.carbon.identity.api.server.rule.metadata.common + diff --git a/modules/api-resources/api-resources-full/src/main/webapp/WEB-INF/beans.xml b/modules/api-resources/api-resources-full/src/main/webapp/WEB-INF/beans.xml index 9801310b857..3fa00cc159e 100644 --- a/modules/api-resources/api-resources-full/src/main/webapp/WEB-INF/beans.xml +++ b/modules/api-resources/api-resources-full/src/main/webapp/WEB-INF/beans.xml @@ -80,6 +80,7 @@ + @@ -147,6 +148,7 @@ + @@ -210,6 +212,8 @@ + + @@ -423,15 +427,6 @@ - - - - - - - - - diff --git a/modules/api-resources/pom.xml b/modules/api-resources/pom.xml index 63c91008f21..6a2fac4e2e9 100644 --- a/modules/api-resources/pom.xml +++ b/modules/api-resources/pom.xml @@ -23,12 +23,12 @@ org.wso2.is identity-server-parent - 7.1.0-m5-SNAPSHOT + 7.1.0-m6-SNAPSHOT ../../pom.xml api-resources - 7.1.0-m5-SNAPSHOT + 7.1.0-m6-SNAPSHOT pom WSO2 Identity Server - Rest API @@ -515,6 +515,16 @@ org.wso2.carbon.identity.api.server.action.management.common ${identity.server.api.version} + + org.wso2.carbon.identity.server.api + org.wso2.carbon.identity.api.server.rule.metadata.v1 + ${identity.server.api.version} + + + org.wso2.carbon.identity.server.api + org.wso2.carbon.identity.api.server.rule.metadata.common + ${identity.server.api.version} + @@ -532,11 +542,6 @@ org.wso2.carbon.identity.api.user.governance ${identity.governance.version} - - org.wso2.carbon.identity.framework - org.wso2.carbon.identity.api.server.entitlement - ${carbon.identity.framework.version} - org.wso2.carbon.identity.framework org.wso2.carbon.identity.api.server.configuration.mgt @@ -557,11 +562,6 @@ org.wso2.carbon.api.server.consent.mgt ${carbon.consent.mgt.version} - - org.wso2.carbon.consent.mgt - org.wso2.carbon.api.server.consent.mgt - ${carbon.consent.mgt.version} - org.wso2.carbon.identity.local.auth.api org.wso2.carbon.api.server.local.auth.api diff --git a/modules/authenticators/pom.xml b/modules/authenticators/pom.xml index 8efe358f734..1c65ce9c06f 100644 --- a/modules/authenticators/pom.xml +++ b/modules/authenticators/pom.xml @@ -19,7 +19,7 @@ org.wso2.is identity-server-parent - 7.1.0-m5-SNAPSHOT + 7.1.0-m6-SNAPSHOT ../../pom.xml 4.0.0 diff --git a/modules/connectors/pom.xml b/modules/connectors/pom.xml index c92af98df42..8b5a2404b43 100644 --- a/modules/connectors/pom.xml +++ b/modules/connectors/pom.xml @@ -19,7 +19,7 @@ org.wso2.is identity-server-parent - 7.1.0-m5-SNAPSHOT + 7.1.0-m6-SNAPSHOT ../../pom.xml 4.0.0 diff --git a/modules/distribution/pom.xml b/modules/distribution/pom.xml index d850c76813e..aa8a32075f3 100755 --- a/modules/distribution/pom.xml +++ b/modules/distribution/pom.xml @@ -19,7 +19,7 @@ org.wso2.is identity-server-parent - 7.1.0-m5-SNAPSHOT + 7.1.0-m6-SNAPSHOT ../../pom.xml @@ -139,7 +139,6 @@ ${basedir}/../p2-profile-gen/target/wso2carbon-core-${carbon.kernel.version}/repository/resources/conf/org.wso2.carbon.event.processor.manager.core.default.json ${basedir}/../p2-profile-gen/target/wso2carbon-core-${carbon.kernel.version}/repository/resources/conf/org.wso2.carbon.identity.application.authentication.framework.server.feature.default.json ${basedir}/../p2-profile-gen/target/wso2carbon-core-${carbon.kernel.version}/repository/resources/conf/org.wso2.carbon.identity.event.server.feature.default.json - ${basedir}/../p2-profile-gen/target/wso2carbon-core-${carbon.kernel.version}/repository/resources/conf/org.wso2.carbon.identity.xacml.server.feature.default.json ${basedir}/../p2-profile-gen/target/wso2carbon-core-${carbon.kernel.version}/repository/resources/conf/org.wso2.carbon.identity.captcha.server.feature.default.json ${basedir}/../p2-profile-gen/target/wso2carbon-core-${carbon.kernel.version}/repository/resources/conf/org.wso2.carbon.identity.scim2.common.feature.default.json ${basedir}/../p2-profile-gen/target/wso2carbon-core-${carbon.kernel.version}/repository/resources/conf/org.wso2.carbon.identity.scim.common.feature.default.json @@ -187,7 +186,6 @@ ${basedir}/../p2-profile-gen/target/wso2carbon-core-${carbon.kernel.version}/repository/resources/conf/org.wso2.carbon.identity.core.server.feature.unit-resolve.json ${basedir}/../p2-profile-gen/target/wso2carbon-core-${carbon.kernel.version}/repository/resources/conf/org.wso2.carbon.event.output.adapter.unit-resolve.json ${basedir}/../p2-profile-gen/target/wso2carbon-core-${carbon.kernel.version}/repository/resources/conf/org.wso2.carbon.identity.event.server.feature.unit-resolve.json - ${basedir}/../p2-profile-gen/target/wso2carbon-core-${carbon.kernel.version}/repository/resources/conf/org.wso2.carbon.identity.xacml.server.feature.unit-resolve.json ${basedir}/../p2-profile-gen/target/wso2carbon-core-${carbon.kernel.version}/repository/resources/conf/unit-resolve.json true @@ -210,7 +208,6 @@ - @@ -582,23 +579,7 @@ org.apache.maven.plugins maven-site-plugin - 3.3 - - - - org.apache.maven.plugins - maven-project-info-reports-plugin - 2.4 - - - - index - - - - - - + 3.21.0 package @@ -638,13 +619,6 @@ - - - - com.google.code.maven-config-processor-plugin - config-processor-maven-plugin - 2.6 - add-missing-axis2-configs prepare-package @@ -783,11 +757,12 @@ - + diff --git a/modules/distribution/registry_config_change.xml.j2 b/modules/distribution/registry_config_change.xml.j2 index 726adf857cd..52fc7fa923a 100644 --- a/modules/distribution/registry_config_change.xml.j2 +++ b/modules/distribution/registry_config_change.xml.j2 @@ -51,17 +51,4 @@ ]]> - - - //wso2registry/staticConfiguration - - - - application/xacml-policy+xml - - - ]]> - - diff --git a/modules/distribution/src/assembly/bin.xml b/modules/distribution/src/assembly/bin.xml index 65218c78949..3edd2fc81f7 100644 --- a/modules/distribution/src/assembly/bin.xml +++ b/modules/distribution/src/assembly/bin.xml @@ -181,6 +181,17 @@ **/ + + + + ../p2-profile-gen/target/wso2carbon-core-${carbon.kernel.version}/repository/resources/identity/rulemeta + + wso2is-${pom.version}/repository/resources/identity/rulemeta + + **/*.json + + + src/repository/resources/conf/templates wso2is-${pom.version}/repository/resources/conf/templates @@ -392,11 +403,6 @@ - - conf/policies - wso2is-${pom.version}/repository/resources/identity/policies/xacml/default - - @@ -759,13 +765,6 @@ wso2is-${pom.version}/repository/conf/identity 644 - - - ../p2-profile-gen/target/wso2carbon-core-${carbon.kernel.version}/repository/conf/identity/entitlement.properties - - wso2is-${pom.version}/repository/conf/identity - 644 - ../p2-profile-gen/target/wso2carbon-core-${carbon.kernel.version}/repository/resources/identity/pages/samlsso_response.html @@ -826,13 +825,6 @@ wso2is-${pom.version}/repository/conf/security 644 - - - ../p2-profile-gen/target/wso2carbon-core-${carbon.kernel.version}/repository/conf/security/balana-config.xml - - wso2is-${pom.version}/repository/conf/security - 644 - ../p2-profile-gen/target/wso2carbon-core-${carbon.kernel.version}/lib/org.wso2.ciphertool-${cipher-tool.version}.jar @@ -966,22 +958,6 @@ wso2is-${pom.version}/repository/conf/ 644 - - - ../p2-profile-gen/target/wso2carbon-core-${carbon.kernel.version}/repository/resources/identity/policies/xacml/default/scope_based_token_validation_policy_template.xml - - wso2is-${pom.version}/repository/resources/identity/policies/xacml/default - - 644 - - - - ../p2-profile-gen/target/wso2carbon-core-${carbon.kernel.version}/repository/resources/identity/policies/xacml/default/scope_based_token_issuance_policy_template.xml - - wso2is-${pom.version}/repository/resources/identity/policies/xacml/default - - 644 - ../p2-profile-gen/target/wso2carbon-core-${carbon.kernel.version}/repository/conf/security/certificate-validation.xml diff --git a/modules/distribution/src/repository/resources/conf/deployment.toml b/modules/distribution/src/repository/resources/conf/deployment.toml index 918af13fd60..c63761c7286 100644 --- a/modules/distribution/src/repository/resources/conf/deployment.toml +++ b/modules/distribution/src/repository/resources/conf/deployment.toml @@ -39,6 +39,9 @@ hash= "66cd9688a2ae068244ea01e70f0e230f5623b7fa4cdecb65070a09ec06452262" [identity.auth_framework.endpoint] app_password= "dashboard" +[notification_templates] +enable_unicode_support = true + # The KeyStore which is used for encrypting/decrypting internal data. By default the primary keystore is used as the internal keystore. #[keystore.internal] diff --git a/modules/features/org.wso2.identity.styles.feature/pom.xml b/modules/features/org.wso2.identity.styles.feature/pom.xml index f0693c4e960..68e82256b80 100644 --- a/modules/features/org.wso2.identity.styles.feature/pom.xml +++ b/modules/features/org.wso2.identity.styles.feature/pom.xml @@ -20,7 +20,7 @@ org.wso2.is identity-features - 7.1.0-m5-SNAPSHOT + 7.1.0-m6-SNAPSHOT ../pom.xml diff --git a/modules/features/org.wso2.identity.ui.feature/pom.xml b/modules/features/org.wso2.identity.ui.feature/pom.xml index b6ca78a80c2..8909cd30f0a 100644 --- a/modules/features/org.wso2.identity.ui.feature/pom.xml +++ b/modules/features/org.wso2.identity.ui.feature/pom.xml @@ -20,7 +20,7 @@ org.wso2.is identity-features - 7.1.0-m5-SNAPSHOT + 7.1.0-m6-SNAPSHOT ../pom.xml diff --git a/modules/features/org.wso2.identity.utils.feature/pom.xml b/modules/features/org.wso2.identity.utils.feature/pom.xml index 7a01c174543..da2e48977f1 100644 --- a/modules/features/org.wso2.identity.utils.feature/pom.xml +++ b/modules/features/org.wso2.identity.utils.feature/pom.xml @@ -20,7 +20,7 @@ org.wso2.is identity-features - 7.1.0-m5-SNAPSHOT + 7.1.0-m6-SNAPSHOT ../pom.xml diff --git a/modules/features/pom.xml b/modules/features/pom.xml index 4f40ef2e384..c027be0cdb5 100644 --- a/modules/features/pom.xml +++ b/modules/features/pom.xml @@ -17,7 +17,7 @@ org.wso2.is identity-server-parent - 7.1.0-m5-SNAPSHOT + 7.1.0-m6-SNAPSHOT ../../pom.xml diff --git a/modules/integration-ui-templates/pom.xml b/modules/integration-ui-templates/pom.xml index 07647fad644..02f9affd269 100644 --- a/modules/integration-ui-templates/pom.xml +++ b/modules/integration-ui-templates/pom.xml @@ -22,7 +22,7 @@ org.wso2.is identity-server-parent - 7.1.0-m5-SNAPSHOT + 7.1.0-m6-SNAPSHOT ../../pom.xml @@ -77,6 +77,16 @@ org.wso2.carbon.identity.integration.ui.templates.applications.microsoft-365 zip + + org.wso2.carbon.identity.integration.ui.templates + org.wso2.carbon.identity.integration.ui.templates.applications.zoom + zip + + + org.wso2.carbon.identity.integration.ui.templates + org.wso2.carbon.identity.integration.ui.templates.applications.slack + zip + diff --git a/modules/integration/pom.xml b/modules/integration/pom.xml index b63df326048..1fd4f003557 100644 --- a/modules/integration/pom.xml +++ b/modules/integration/pom.xml @@ -19,7 +19,7 @@ org.wso2.is identity-server-parent - 7.1.0-m5-SNAPSHOT + 7.1.0-m6-SNAPSHOT ../../pom.xml diff --git a/modules/integration/tests-common/admin-clients/pom.xml b/modules/integration/tests-common/admin-clients/pom.xml index d1bd5192d9b..0b1bfc0d3cf 100644 --- a/modules/integration/tests-common/admin-clients/pom.xml +++ b/modules/integration/tests-common/admin-clients/pom.xml @@ -19,7 +19,7 @@ org.wso2.is identity-integration-tests - 7.1.0-m5-SNAPSHOT + 7.1.0-m6-SNAPSHOT ../../pom.xml @@ -67,10 +67,6 @@ org.wso2.carbon.identity.inbound.auth.oauth2 org.wso2.carbon.identity.oauth.stub - - org.wso2.carbon.identity.framework - org.wso2.carbon.identity.entitlement.stub - org.wso2.carbon.automationutils org.wso2.carbon.integration.common.admin.client diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/identity/integration/common/clients/KeyStoreAdminClient.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/identity/integration/common/clients/KeyStoreAdminClient.java index f726273a85f..02fcf401142 100644 --- a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/identity/integration/common/clients/KeyStoreAdminClient.java +++ b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/identity/integration/common/clients/KeyStoreAdminClient.java @@ -38,6 +38,7 @@ import org.wso2.carbon.security.mgt.stub.keystore.RemoveCertFromStore; import org.wso2.carbon.security.mgt.stub.keystore.xsd.KeyStoreData; import org.wso2.carbon.security.mgt.stub.keystore.xsd.PaginatedKeyStoreData; +import org.wso2.carbon.utils.security.KeystoreUtils; import java.io.ByteArrayInputStream; import java.rmi.RemoteException; @@ -143,7 +144,7 @@ public boolean isPrivateKeyStore(byte[] content, String password, String type) try { boolean isPrivateStore = false; ByteArrayInputStream stream = new ByteArrayInputStream(content); - KeyStore store = KeyStore.getInstance(type); + KeyStore store = KeystoreUtils.getKeystoreInstance(type); store.load(stream, password.toCharArray()); Enumeration aliases = store.aliases(); while (aliases.hasMoreElements()) { diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/identity/integration/common/clients/entitlement/EntitlementAdminServiceClient.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/identity/integration/common/clients/entitlement/EntitlementAdminServiceClient.java deleted file mode 100644 index e576e705daa..00000000000 --- a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/identity/integration/common/clients/entitlement/EntitlementAdminServiceClient.java +++ /dev/null @@ -1,130 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. licenses this file to you under the Apache License, -* Version 2.0 (the "License"); you may not use this file except -* in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, -* software distributed under the License is distributed on an -* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -* KIND, either express or implied. See the License for the -* specific language governing permissions and limitations -* under the License. -*/ - -package org.wso2.identity.integration.common.clients.entitlement; - -import java.rmi.RemoteException; - -import org.apache.axis2.AxisFault; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.entitlement.stub.dto.PolicyFinderDataHolder; -import org.wso2.carbon.identity.entitlement.stub.dto.PIPFinderDataHolder; -import org.wso2.carbon.identity.entitlement.stub.dto.PDPDataHolder; -import org.wso2.carbon.identity.entitlement.stub.EntitlementAdminServiceIdentityException; -import org.wso2.carbon.identity.entitlement.stub.EntitlementAdminServiceStub; -import org.wso2.identity.integration.common.clients.AuthenticateStub; - -public class EntitlementAdminServiceClient { - - private static final Log log = LogFactory.getLog(EntitlementAdminServiceClient.class); - - private final String serviceName = "EntitlementAdminService"; - private EntitlementAdminServiceStub entitlementAdminServiceStub; - private String endPoint; - - public EntitlementAdminServiceClient(String backEndUrl, String sessionCookie) - throws AxisFault { - this.endPoint = backEndUrl + serviceName; - entitlementAdminServiceStub = new EntitlementAdminServiceStub(endPoint); - AuthenticateStub.authenticateStub(sessionCookie, entitlementAdminServiceStub); - } - - public EntitlementAdminServiceClient(String backEndUrl, String userName, String password) - throws AxisFault { - this.endPoint = backEndUrl + serviceName; - entitlementAdminServiceStub = new EntitlementAdminServiceStub(endPoint); - AuthenticateStub.authenticateStub(userName, password, entitlementAdminServiceStub); - } - - public String getGlobalPolicyAlgorithm() throws RemoteException{ - String algo = null; - try { - algo = entitlementAdminServiceStub.getGlobalPolicyAlgorithm(); - } catch (EntitlementAdminServiceIdentityException e) { - e.printStackTrace(); - } - return algo; - } - - public String doTestRequest(String xacmlRequest) throws RemoteException{ - String requestStatus = null; - try { - requestStatus = entitlementAdminServiceStub.doTestRequest(xacmlRequest); - } catch (EntitlementAdminServiceIdentityException e) { - e.printStackTrace(); - } - return requestStatus; - } - - public PDPDataHolder getPDPData() throws RemoteException{ - PDPDataHolder holder = null; - holder = entitlementAdminServiceStub.getPDPData(); - return holder; - } - - public PIPFinderDataHolder getPIPAttributeFinderData(String finder) throws RemoteException{ - PIPFinderDataHolder holder = null; - holder = entitlementAdminServiceStub.getPIPAttributeFinderData(finder); - return holder; - } - - public PIPFinderDataHolder getPIPResourceFinderData(String finder) throws RemoteException{ - PIPFinderDataHolder holder = null; - holder = entitlementAdminServiceStub.getPIPResourceFinderData(finder); - return holder; - } - - public PolicyFinderDataHolder getPolicyFinderData(String finder) throws RemoteException{ - PolicyFinderDataHolder holder = null; - holder = entitlementAdminServiceStub.getPolicyFinderData(finder); - return holder; - } - - public void refreshAttributeFinder(String attributeFinder) throws RemoteException{ - try { - entitlementAdminServiceStub.refreshAttributeFinder(attributeFinder); - } catch (EntitlementAdminServiceIdentityException e) { - e.printStackTrace(); - } - } - - public void refreshPolicyFinders(String policyFinder) throws RemoteException{ - try { - entitlementAdminServiceStub.refreshPolicyFinders(policyFinder); - } catch (EntitlementAdminServiceIdentityException e) { - e.printStackTrace(); - } - } - - public void refreshResourceFinder(String resourceFinder) throws RemoteException{ - try { - entitlementAdminServiceStub.refreshResourceFinder(resourceFinder); - } catch (EntitlementAdminServiceIdentityException e) { - e.printStackTrace(); - } - } - - public void setGlobalPolicyAlgorithm(String policyCombiningAlgorithm) throws RemoteException{ - try { - entitlementAdminServiceStub.setGlobalPolicyAlgorithm(policyCombiningAlgorithm); - } catch (EntitlementAdminServiceIdentityException e) { - e.printStackTrace(); - } - } -} diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/identity/integration/common/clients/entitlement/EntitlementPolicyServiceClient.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/identity/integration/common/clients/entitlement/EntitlementPolicyServiceClient.java deleted file mode 100644 index c58386aa2f0..00000000000 --- a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/identity/integration/common/clients/entitlement/EntitlementPolicyServiceClient.java +++ /dev/null @@ -1,256 +0,0 @@ -/* -*Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -*WSO2 Inc. licenses this file to you under the Apache License, -*Version 2.0 (the "License"); you may not use this file except -*in compliance with the License. -*You may obtain a copy of the License at -* -*http://www.apache.org/licenses/LICENSE-2.0 -* -*Unless required by applicable law or agreed to in writing, -*software distributed under the License is distributed on an -*"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -*KIND, either express or implied. See the License for the -*specific language governing permissions and limitations -*under the License. -*/ - -package org.wso2.identity.integration.common.clients.entitlement; - -import org.apache.axis2.AxisFault; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.entitlement.stub.dto.PaginatedPolicySetDTO; -import org.wso2.carbon.identity.entitlement.stub.EntitlementPolicyAdminServiceEntitlementException; -import org.wso2.carbon.identity.entitlement.stub.EntitlementPolicyAdminServiceStub; -import org.wso2.carbon.identity.entitlement.stub.dto.PaginatedStatusHolder; -import org.wso2.carbon.identity.entitlement.stub.dto.PolicyDTO; -import org.wso2.carbon.identity.entitlement.stub.dto.PublisherDataHolder; -import org.wso2.identity.integration.common.clients.AuthenticateStub; -import org.xml.sax.SAXException; - -import javax.activation.DataHandler; -import javax.activation.FileDataSource; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -import java.io.*; -import java.rmi.RemoteException; - -public class EntitlementPolicyServiceClient { - private static final Log log = LogFactory.getLog(EntitlementPolicyServiceClient.class); - - private final String serviceName = "EntitlementPolicyAdminService"; - private EntitlementPolicyAdminServiceStub entitlementPolicyAdminServiceStub; - private String endPoint; - - public EntitlementPolicyServiceClient(String backEndUrl, String sessionCookie) - throws AxisFault { - this.endPoint = backEndUrl + serviceName; - entitlementPolicyAdminServiceStub = new EntitlementPolicyAdminServiceStub(endPoint); - AuthenticateStub.authenticateStub(sessionCookie, entitlementPolicyAdminServiceStub); - } - - public EntitlementPolicyServiceClient(String backEndUrl, String userName, String password) - throws AxisFault { - this.endPoint = backEndUrl + serviceName; - entitlementPolicyAdminServiceStub = new EntitlementPolicyAdminServiceStub(endPoint); - AuthenticateStub.authenticateStub(userName, password, entitlementPolicyAdminServiceStub); - } - - public void addPolicies(File policyFile) - throws IOException, - ParserConfigurationException, TransformerException, SAXException, - EntitlementPolicyAdminServiceEntitlementException { - - DataHandler policydh = - new DataHandler(new FileDataSource(policyFile)); - String policy = convertXMLFileToString(policyFile); - - PolicyDTO policySetDTO = new PolicyDTO(); - policySetDTO.setPolicy(policy); - policySetDTO.setActive(true); - entitlementPolicyAdminServiceStub.addPolicy(policySetDTO); - } - - public void removePolicy(String policyId) - throws IOException, EntitlementPolicyAdminServiceEntitlementException { - entitlementPolicyAdminServiceStub.removePolicy(policyId, false); - } - - public void removePolicy(String policyId, boolean dePromote) - throws IOException, EntitlementPolicyAdminServiceEntitlementException { - entitlementPolicyAdminServiceStub.removePolicy(policyId, dePromote); - } - - public void updatePolicy(PolicyDTO policyDTO) throws RemoteException, EntitlementPolicyAdminServiceEntitlementException { - entitlementPolicyAdminServiceStub.updatePolicy(policyDTO); - } - - public void removePolicies(String[] policies, boolean dePromote) throws RemoteException { - try { - entitlementPolicyAdminServiceStub.removePolicies(policies, dePromote); - } catch (EntitlementPolicyAdminServiceEntitlementException e) { - log.error(e); - } - } - - public String[] getAllPolicyIds(String searchString) throws RemoteException, EntitlementPolicyAdminServiceEntitlementException { - return entitlementPolicyAdminServiceStub.getAllPolicyIds(searchString); - } - - public void addPolicy(PolicyDTO policyDTO) throws RemoteException, EntitlementPolicyAdminServiceEntitlementException { - entitlementPolicyAdminServiceStub.addPolicy(policyDTO); - } - - public void addPolicies(PolicyDTO[] policies) throws RemoteException { - try { - entitlementPolicyAdminServiceStub.addPolicies(policies); - } catch (EntitlementPolicyAdminServiceEntitlementException e) { - log.error(e); - } - } - - public PolicyDTO getPolicy(String policyId, boolean isPDPPolicy) throws RemoteException, EntitlementPolicyAdminServiceEntitlementException { - return entitlementPolicyAdminServiceStub.getPolicy(policyId, isPDPPolicy); - } - - public String[] getPolicyVersions(String policyId) throws RemoteException, EntitlementPolicyAdminServiceEntitlementException { - return entitlementPolicyAdminServiceStub.getPolicyVersions(policyId); - } - - public PaginatedPolicySetDTO getAllPolicies(String policyTypeFilter, String policySearchString, - int pageNumber, boolean isPDPPolicy) throws RemoteException, EntitlementPolicyAdminServiceEntitlementException { - return entitlementPolicyAdminServiceStub.getAllPolicies(policyTypeFilter, policySearchString, pageNumber, isPDPPolicy); - } - - public PolicyDTO getPolicyByVersion(String policyId, String version) throws RemoteException, EntitlementPolicyAdminServiceEntitlementException { - return entitlementPolicyAdminServiceStub.getPolicyByVersion(policyId, version); - } - - public void importPolicyFromRegistry(String policyRegistryPath) throws RemoteException, EntitlementPolicyAdminServiceEntitlementException { - entitlementPolicyAdminServiceStub.importPolicyFromRegistry(policyRegistryPath); - } - - public PaginatedStatusHolder getStatusData(String about, String key, String type, - String searchString, int pageNumber) throws RemoteException { - - PaginatedStatusHolder holder = null; - try { - holder = entitlementPolicyAdminServiceStub.getStatusData(about, key, type, searchString, pageNumber); - } catch (EntitlementPolicyAdminServiceEntitlementException e) { - log.error(e); - } - return holder; - } - - public void addSubscriber(PublisherDataHolder holder) throws RemoteException { - try { - entitlementPolicyAdminServiceStub.addSubscriber(holder); - } catch (EntitlementPolicyAdminServiceEntitlementException e) { - log.error(e); - } - } - - public void updateSubscriber(PublisherDataHolder holder) throws RemoteException { - try { - entitlementPolicyAdminServiceStub.updateSubscriber(holder); - } catch (EntitlementPolicyAdminServiceEntitlementException e) { - log.error(e); - } - } - - public PublisherDataHolder getSubscriber(String subscribeId) throws RemoteException { - PublisherDataHolder holder = null; - try { - holder = entitlementPolicyAdminServiceStub.getSubscriber(subscribeId); - } catch (EntitlementPolicyAdminServiceEntitlementException e) { - log.error(e); - } - return holder; - } - - public String[] getSubscriberIds(String searchString) throws RemoteException { - String[] ids = null; - try { - ids = entitlementPolicyAdminServiceStub.getSubscriberIds(searchString); - } catch (EntitlementPolicyAdminServiceEntitlementException e) { - log.error(e); - } - return ids; - } - - public void deleteSubscriber(String subscriberId) throws RemoteException { - try { - entitlementPolicyAdminServiceStub.deleteSubscriber(subscriberId); - } catch (EntitlementPolicyAdminServiceEntitlementException e) { - log.error(e); - } - } - - public void enableDisablePolicy(String policyId, boolean enable) throws RemoteException { - try { - entitlementPolicyAdminServiceStub.enableDisablePolicy(policyId, enable); - } catch (EntitlementPolicyAdminServiceEntitlementException e) { - log.error(e); - } - } - - public void publish(String verificationCode) throws RemoteException { - try { - entitlementPolicyAdminServiceStub.publish(verificationCode); - } catch (EntitlementPolicyAdminServiceEntitlementException e) { - log.error(e); - } - } - - public void publishToPDP(String[] policies, String action, boolean enabled, String version, int order) throws RemoteException { - try { - entitlementPolicyAdminServiceStub.publishToPDP(policies, action, version, enabled, order); - } catch (EntitlementPolicyAdminServiceEntitlementException e) { - log.error(e); - } - } - - public void publishPolicies(String[] policies, String[] subscriberIds, String action, boolean enabled, String version, int order) throws RemoteException { - try { - entitlementPolicyAdminServiceStub.publishPolicies(policies, subscriberIds, action, version, enabled, order); - } catch (EntitlementPolicyAdminServiceEntitlementException e) { - log.error(e); - } - } - - public void orderPolicy(String policyId, int newOrder) throws RemoteException { - try { - entitlementPolicyAdminServiceStub.orderPolicy(policyId, newOrder); - } catch (EntitlementPolicyAdminServiceEntitlementException e) { - log.error(e); - } - } - - public void dePromotePolicy(String policyId) throws RemoteException { - try { - entitlementPolicyAdminServiceStub.dePromotePolicy(policyId); - } catch (EntitlementPolicyAdminServiceEntitlementException e) { - log.error(e); - } - } - - private String convertXMLFileToString(File fileName) - throws IOException, ParserConfigurationException, SAXException, TransformerException { - - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - InputStream inputStream = new FileInputStream(fileName); - org.w3c.dom.Document doc = documentBuilderFactory.newDocumentBuilder().parse(inputStream); - StringWriter stw = new StringWriter(); - Transformer serializer = TransformerFactory.newInstance().newTransformer(); - serializer.transform(new DOMSource(doc), new StreamResult(stw)); - return stw.toString(); - } -} diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/identity/integration/common/clients/entitlement/EntitlementServiceClient.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/identity/integration/common/clients/entitlement/EntitlementServiceClient.java deleted file mode 100644 index ddc5992e59e..00000000000 --- a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/identity/integration/common/clients/entitlement/EntitlementServiceClient.java +++ /dev/null @@ -1,109 +0,0 @@ -/** - * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.wso2.identity.integration.common.clients.entitlement; - -import org.apache.axis2.AxisFault; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.identity.entitlement.stub.EntitlementServiceCallbackHandler; -import org.wso2.carbon.identity.entitlement.stub.EntitlementServiceException; -import org.wso2.carbon.identity.entitlement.stub.EntitlementServiceIdentityException; -import org.wso2.carbon.identity.entitlement.stub.EntitlementServiceStub; -import org.wso2.carbon.identity.entitlement.stub.dto.AttributeDTO; -import org.wso2.carbon.identity.entitlement.stub.dto.EntitledResultSetDTO; -import org.wso2.identity.integration.common.clients.AuthenticateStub; - -import java.rmi.RemoteException; - -public class EntitlementServiceClient { - private static final Log log = LogFactory.getLog(EntitlementServiceClient.class); - - private final String serviceName = "EntitlementService"; - private EntitlementServiceStub entitlementServiceStub; - private String endPoint; - - public EntitlementServiceClient(String backEndUrl, String sessionCookie) throws AxisFault { - this.endPoint = backEndUrl + serviceName; - entitlementServiceStub = new EntitlementServiceStub(endPoint); - AuthenticateStub.authenticateStub(sessionCookie, entitlementServiceStub); - } - - public EntitlementServiceClient(String backEndUrl, String userName, String password) throws AxisFault { - this.endPoint = backEndUrl + serviceName; - entitlementServiceStub = new EntitlementServiceStub(endPoint); - AuthenticateStub.authenticateStub(userName, password, entitlementServiceStub); - } - - public EntitledResultSetDTO getEntitledAttributes(String subjectName, String resourceName, String subjectId, - String action, boolean enableChildSearch) - throws RemoteException, EntitlementServiceIdentityException { - return entitlementServiceStub.getEntitledAttributes(subjectName, resourceName, subjectId, action, enableChildSearch); - } - - public void startgetEntitledAttributes(String subjectName, String resourceName, String subjectId, - String action, boolean enableChildSearch, EntitlementServiceCallbackHandler callback) - throws RemoteException { - entitlementServiceStub.startgetEntitledAttributes(subjectName, resourceName, subjectId, action, enableChildSearch, callback); - } - - public String xACMLAuthzDecisionQuery(String request) throws EntitlementServiceException, RemoteException { - return entitlementServiceStub.xACMLAuthzDecisionQuery(request); - } - - public void startxACMLAuthzDecisionQuery(String request, EntitlementServiceCallbackHandler callback) - throws RemoteException { - entitlementServiceStub.startxACMLAuthzDecisionQuery(request, callback); - } - - public EntitledResultSetDTO getAllEntitlements(String identifier, AttributeDTO[] givenAttributes) - throws RemoteException, EntitlementServiceIdentityException { - return entitlementServiceStub.getAllEntitlements(identifier, givenAttributes); - } - - public void startgetAllEntitlements(String identifier, AttributeDTO[] givenAttributes, - EntitlementServiceCallbackHandler callback) throws RemoteException { - entitlementServiceStub.startgetAllEntitlements(identifier, givenAttributes, callback); - } - - public String getDecision(String request) throws EntitlementServiceException, RemoteException { - return entitlementServiceStub.getDecision(request); - } - - public void startgetDecision(String request, EntitlementServiceCallbackHandler callback) throws RemoteException { - entitlementServiceStub.startgetDecision(request, callback); - } - - public String getDecisionByAttributes(String subject, String resource, String action, String[] environment) - throws EntitlementServiceException, RemoteException { - return entitlementServiceStub.getDecisionByAttributes(subject, resource, action, environment); - } - - public void startgetDecisionByAttributes(String subject, String resource, String action, String[] environment, - EntitlementServiceCallbackHandler callback) throws RemoteException { - entitlementServiceStub.startgetDecisionByAttributes(subject, resource, action, environment, callback); - } - - public boolean getBooleanDecision(String subject, String resource, String action) - throws EntitlementServiceException, RemoteException { - return entitlementServiceStub.getBooleanDecision(subject, resource, action); - } - - public void startgetBooleanDecision(String subject, String resource, String action, - EntitlementServiceCallbackHandler callback) throws RemoteException { - entitlementServiceStub.startgetBooleanDecision(subject, resource, action, callback); - } -} diff --git a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/identity/integration/common/clients/sso/saml/query/ClientSignKeyDataHolder.java b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/identity/integration/common/clients/sso/saml/query/ClientSignKeyDataHolder.java index ddeb0a68609..ae33b0db335 100644 --- a/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/identity/integration/common/clients/sso/saml/query/ClientSignKeyDataHolder.java +++ b/modules/integration/tests-common/admin-clients/src/main/java/org/wso2/identity/integration/common/clients/sso/saml/query/ClientSignKeyDataHolder.java @@ -24,6 +24,7 @@ import org.opensaml.security.credential.CredentialContextSet; import org.opensaml.security.credential.UsageType; import org.opensaml.security.x509.X509Credential; +import org.wso2.carbon.utils.security.KeystoreUtils; import java.io.File; import java.io.FileInputStream; @@ -59,6 +60,8 @@ public class ClientSignKeyDataHolder implements X509Credential { private PublicKey publicKey = null; + private static final String KEYSTORE_TYPE = "PKCS12"; + /** * Constructor method * @param keyStorePath path to the key store @@ -74,7 +77,7 @@ public ClientSignKeyDataHolder(String keyStorePath, String password, String key try { File file = new File(keyStorePath); is = new FileInputStream(file); - KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); + KeyStore keystore = KeystoreUtils.getKeystoreInstance(KEYSTORE_TYPE); keystore.load(is, password.toCharArray()); privateKey = (PrivateKey) keystore.getKey(keyAlias, password.toCharArray()); diff --git a/modules/integration/tests-common/extensions/pom.xml b/modules/integration/tests-common/extensions/pom.xml index 5a78447b776..e69de29bb2d 100644 --- a/modules/integration/tests-common/extensions/pom.xml +++ b/modules/integration/tests-common/extensions/pom.xml @@ -1,41 +0,0 @@ - - - - - - - org.wso2.is - identity-integration-tests - 7.1.0-m5-SNAPSHOT - ../../pom.xml - - - 4.0.0 - Custom Attribute Finder - org.wso2.carbon.identity.custom.pip - jar - - - - org.wso2.carbon.identity.framework - org.wso2.carbon.identity.entitlement - - - - diff --git a/modules/integration/tests-common/extensions/src/main/java/org/wso2/carbon/identity/custom/pip/CustomAttributeFinder.java b/modules/integration/tests-common/extensions/src/main/java/org/wso2/carbon/identity/custom/pip/CustomAttributeFinder.java deleted file mode 100644 index b5731b30f1b..00000000000 --- a/modules/integration/tests-common/extensions/src/main/java/org/wso2/carbon/identity/custom/pip/CustomAttributeFinder.java +++ /dev/null @@ -1,75 +0,0 @@ -/* -* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. licenses this file to you under the Apache License, -* Version 2.0 (the "License"); you may not use this file except -* in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, -* software distributed under the License is distributed on an -* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -* KIND, either express or implied. See the License for the -* specific language governing permissions and limitations -* under the License. -*/ - -package org.wso2.carbon.identity.custom.pip; - - -import java.util.HashSet; -import java.util.Properties; -import java.util.Set; - -import org.wso2.carbon.identity.entitlement.pip.AbstractPIPAttributeFinder; - -/** - * This class is used by EntitlementPIPAttributeCacheTestCase to simulate the PIP attribute caching scenario. - */ -public class CustomAttributeFinder extends AbstractPIPAttributeFinder { - - - private static final String EMAIL_ID = "http://wso2.org/claims/emailaddress"; - - - /** - * List of attribute finders supported by the this PIP attribute finder - */ - private Set supportedAttributes = new HashSet(); - - @Override - public void init(Properties properties) throws Exception { - supportedAttributes.add(EMAIL_ID); - } - - @Override - public String getModuleName() { - return "Custom Attribute Finder"; - } - - @Override - public boolean overrideDefaultCache() { - return false; - } - - @Override - public Set getAttributeValues(String subjectId, String resourceId, String actionId, - String environmentId, String attributeId, String issuer) throws Exception { - - - Set values = new HashSet(); - if ("admin@wso2.com".equals(subjectId)) { - values.add(subjectId); - } else { - values.add("notexist"); - } - return values; - } - - @Override - public Set getSupportedAttributes() { - return supportedAttributes; - } -} diff --git a/modules/integration/tests-common/integration-test-utils/pom.xml b/modules/integration/tests-common/integration-test-utils/pom.xml index 6bea82aa5f7..68e72fd171c 100644 --- a/modules/integration/tests-common/integration-test-utils/pom.xml +++ b/modules/integration/tests-common/integration-test-utils/pom.xml @@ -19,7 +19,7 @@ org.wso2.is identity-integration-tests - 7.1.0-m5-SNAPSHOT + 7.1.0-m6-SNAPSHOT ../../pom.xml diff --git a/modules/integration/tests-common/jacoco-report-generator/pom.xml b/modules/integration/tests-common/jacoco-report-generator/pom.xml index 83de5aaf985..ba260627b59 100644 --- a/modules/integration/tests-common/jacoco-report-generator/pom.xml +++ b/modules/integration/tests-common/jacoco-report-generator/pom.xml @@ -22,7 +22,7 @@ org.wso2.is identity-integration-tests - 7.1.0-m5-SNAPSHOT + 7.1.0-m6-SNAPSHOT ../../pom.xml diff --git a/modules/integration/tests-common/pom.xml b/modules/integration/tests-common/pom.xml index e0b64ccd5cd..303f1c22ee2 100644 --- a/modules/integration/tests-common/pom.xml +++ b/modules/integration/tests-common/pom.xml @@ -19,7 +19,7 @@ org.wso2.is identity-integration-tests - 7.1.0-m5-SNAPSHOT + 7.1.0-m6-SNAPSHOT ../pom.xml @@ -32,7 +32,6 @@ admin-clients ui-pages integration-test-utils - extensions jacoco-report-generator diff --git a/modules/integration/tests-common/ui-pages/pom.xml b/modules/integration/tests-common/ui-pages/pom.xml index 1a27cbee757..0a01bd787ac 100644 --- a/modules/integration/tests-common/ui-pages/pom.xml +++ b/modules/integration/tests-common/ui-pages/pom.xml @@ -19,7 +19,7 @@ org.wso2.is identity-integration-tests - 7.1.0-m5-SNAPSHOT + 7.1.0-m6-SNAPSHOT ../../pom.xml diff --git a/modules/integration/tests-cypress-integration/tests-identity-apps/src/test/resources/instrumentation.txt b/modules/integration/tests-cypress-integration/tests-identity-apps/src/test/resources/instrumentation.txt index 4bd93d2dfbb..fddfc506bee 100644 --- a/modules/integration/tests-cypress-integration/tests-identity-apps/src/test/resources/instrumentation.txt +++ b/modules/integration/tests-cypress-integration/tests-identity-apps/src/test/resources/instrumentation.txt @@ -25,8 +25,6 @@ org.wso2.carbon.identity.authenticator.saml2.sso.common* org.wso2.carbon.identity.authorization.core* org.wso2.carbon.identity.base* org.wso2.carbon.identity.core* -org.wso2.carbon.identity.entitlement* -org.wso2.carbon.identity.entitlement.common* org.wso2.carbon.identity.mgt* org.wso2.carbon.identity.oauth* org.wso2.carbon.identity.oauth.common* diff --git a/modules/integration/tests-integration/pom.xml b/modules/integration/tests-integration/pom.xml index fd48eb1af64..e749240db12 100644 --- a/modules/integration/tests-integration/pom.xml +++ b/modules/integration/tests-integration/pom.xml @@ -19,7 +19,7 @@ org.wso2.is identity-integration-tests - 7.1.0-m5-SNAPSHOT + 7.1.0-m6-SNAPSHOT ../pom.xml diff --git a/modules/integration/tests-integration/tests-backend/pom.xml b/modules/integration/tests-integration/tests-backend/pom.xml index 2b984b1a3c2..ebf130c74ac 100644 --- a/modules/integration/tests-integration/tests-backend/pom.xml +++ b/modules/integration/tests-integration/tests-backend/pom.xml @@ -18,7 +18,7 @@ org.wso2.is identity-integration-tests - 7.1.0-m5-SNAPSHOT + 7.1.0-m6-SNAPSHOT ../../pom.xml @@ -47,7 +47,7 @@ 2.22.1 - -Xmx1024m + -Xmx1536m -XX:+HeapDumpOnOutOfMemoryError -Dorg.apache.jasper.compiler.disablejsr199=true --add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/java.util=ALL-UNNAMED @@ -446,21 +446,6 @@ run - - packaging-war-artifacts-openid - process-test-resources - - - - - - - - - - run - - packaging-war-artifacts-oauth process-test-resources @@ -473,19 +458,6 @@ run - - packaging-war-artifacts-oidc - process-test-resources - - - - - - - - run - - packaging-war-artifacts-passivests process-test-resources @@ -855,10 +827,6 @@ org.wso2.carbon.identity.inbound.auth.oauth2 org.wso2.carbon.identity.oauth.stub - - org.wso2.carbon.identity.framework - org.wso2.carbon.identity.entitlement.stub - org.wso2.carbon.identity.framework org.wso2.carbon.identity.user.profile.stub diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/IdentityServerTestSuitInitializerTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/IdentityServerTestSuitInitializerTestCase.java index fb9eda85607..bca5435c501 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/IdentityServerTestSuitInitializerTestCase.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/IdentityServerTestSuitInitializerTestCase.java @@ -18,6 +18,7 @@ package org.wso2.identity.integration.test; +import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.testng.annotations.Test; import org.wso2.identity.integration.test.util.Utils; @@ -27,5 +28,10 @@ public class IdentityServerTestSuitInitializerTestCase { public void testInitialize() throws Exception { //save the carbon.home system property Utils.getResidentCarbonHome(); + //add BC provider + BouncyCastleProvider bouncyCastleProvider = new BouncyCastleProvider(); + if (java.security.Security.getProvider(bouncyCastleProvider.getName()) == null) { + java.security.Security.addProvider(bouncyCastleProvider); + } } } diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/PreIssueAccessTokenActionFailureClientCredentialsGrantTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/PreIssueAccessTokenActionFailureClientCredentialsGrantTestCase.java new file mode 100644 index 00000000000..4bacd83e704 --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/PreIssueAccessTokenActionFailureClientCredentialsGrantTestCase.java @@ -0,0 +1,201 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.identity.integration.test.actions; + +import org.apache.http.Header; +import org.apache.http.HttpResponse; +import org.apache.http.NameValuePair; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.message.BasicHeader; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; +import org.json.JSONObject; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; +import org.wso2.carbon.automation.engine.context.TestUserMode; +import org.wso2.identity.integration.test.actions.dataprovider.model.ActionResponse; +import org.wso2.identity.integration.test.actions.dataprovider.model.ExpectedTokenResponse; +import org.wso2.identity.integration.test.actions.mockserver.ActionsMockServer; +import org.wso2.identity.integration.test.rest.api.server.action.management.v1.model.ActionModel; +import org.wso2.identity.integration.test.rest.api.server.action.management.v1.model.AuthenticationType; +import org.wso2.identity.integration.test.rest.api.server.action.management.v1.model.Endpoint; +import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.ApplicationResponseModel; +import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.OpenIDConnectConfiguration; +import org.wso2.identity.integration.test.utils.FileUtils; +import org.wso2.identity.integration.test.utils.OAuth2Constant; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.wso2.identity.integration.test.utils.OAuth2Constant.ACCESS_TOKEN_ENDPOINT; +import static org.wso2.identity.integration.test.utils.OAuth2Constant.AUTHORIZATION_HEADER; + +/** + * Tests the pre-issue access token action failure scenarios with password grant type. + */ +public class PreIssueAccessTokenActionFailureClientCredentialsGrantTestCase extends ActionsBaseTestCase { + + private static final String USERNAME_PROPERTY = "username"; + private static final String PASSWORD_PROPERTY = "password"; + private static final String EXTERNAL_SERVICE_URI = "http://localhost:8587/test/action"; + private static final String PRE_ISSUE_ACCESS_TOKEN_API_PATH = "preIssueAccessToken"; + private static final String MOCK_SERVER_ENDPOINT_RESOURCE_PATH = "/test/action"; + private static final String MOCK_SERVER_AUTH_BASIC_USERNAME = "test"; + private static final String MOCK_SERVER_AUTH_BASIC_PASSWORD = "test"; + private static final String CLIENT_CREDENTIALS_GRANT_TYPE = "client_credentials"; + private CloseableHttpClient client; + private List requestedScopes; + private String clientId; + private String clientSecret; + private String actionId; + private String applicationId; + private final TestUserMode userMode; + private ActionsMockServer actionsMockServer; + private final ActionResponse actionResponse; + private final ExpectedTokenResponse expectedTokenResponse; + + @Factory(dataProvider = "testExecutionContextProvider") + public PreIssueAccessTokenActionFailureClientCredentialsGrantTestCase(TestUserMode testUserMode, + ActionResponse actionResponse, + ExpectedTokenResponse expectedTokenResponse) { + + this.userMode = testUserMode; + this.actionResponse = actionResponse; + this.expectedTokenResponse = expectedTokenResponse; + } + + @DataProvider(name = "testExecutionContextProvider") + public static Object[][] getTestExecutionContext() throws Exception { + + return new Object[][]{ + {TestUserMode.SUPER_TENANT_USER, new ActionResponse(200, + FileUtils.readFileInClassPathAsString("actions/response/failure-response.json")), + new ExpectedTokenResponse(400, "Some failure reason", "Some description")}, + {TestUserMode.TENANT_USER, new ActionResponse(200, + FileUtils.readFileInClassPathAsString("actions/response/failure-response.json")), + new ExpectedTokenResponse(400, "Some failure reason", "Some description")}, + {TestUserMode.TENANT_USER, new ActionResponse(500, + FileUtils.readFileInClassPathAsString("actions/response/error-response.json")), + new ExpectedTokenResponse(500, "server_error", "Internal Server Error.")}, + {TestUserMode.TENANT_USER, new ActionResponse(401, "Unauthorized"), + new ExpectedTokenResponse(500, "server_error", "Internal Server Error.")}, + }; + } + + @BeforeClass(alwaysRun = true) + public void testInit() throws Exception { + + super.init(userMode); + client = HttpClientBuilder.create().build(); + + ApplicationResponseModel application = addApplicationWithGrantType(CLIENT_CREDENTIALS_GRANT_TYPE); + applicationId = application.getId(); + OpenIDConnectConfiguration oidcConfig = getOIDCInboundDetailsOfApplication(applicationId); + clientId = oidcConfig.getClientId(); + clientSecret = oidcConfig.getClientSecret(); + actionId = createPreIssueAccessTokenAction(); + + requestedScopes = new ArrayList<>(Arrays.asList("scope_1", "scope_2")); + + actionsMockServer = new ActionsMockServer(); + actionsMockServer.startServer(); + actionsMockServer.setupStub(MOCK_SERVER_ENDPOINT_RESOURCE_PATH, + "Basic " + getBase64EncodedString(MOCK_SERVER_AUTH_BASIC_USERNAME, MOCK_SERVER_AUTH_BASIC_PASSWORD), + actionResponse.getResponseBody(), actionResponse.getStatusCode()); + } + + @AfterClass(alwaysRun = true) + public void atEnd() throws Exception { + + actionsMockServer.stopServer(); + + deleteAction(PRE_ISSUE_ACCESS_TOKEN_API_PATH, actionId); + deleteApp(applicationId); + + restClient.closeHttpClient(); + actionsRestClient.closeHttpClient(); + client.close(); + + actionsMockServer = null; + } + + @Test(groups = "wso2.is", description = "Verify token response when pre-issue access token action fails with " + + "client credentials grant type.") + public void testPreIssueAccessTokenActionFailure() throws Exception { + + HttpResponse response = sendTokenRequestForClientCredentialsGrant(); + + assertNotNull(response); + assertEquals(response.getStatusLine().getStatusCode(), expectedTokenResponse.getStatusCode()); + + String responseString = EntityUtils.toString(response.getEntity(), "UTF-8"); + JSONObject jsonResponse = new JSONObject(responseString); + assertEquals(jsonResponse.getString("error"), expectedTokenResponse.getErrorMessage()); + assertEquals(jsonResponse.getString("error_description"), expectedTokenResponse.getErrorDescription()); + } + + public HttpResponse sendTokenRequestForClientCredentialsGrant() throws Exception { + + List parameters = new ArrayList<>(); + parameters.add(new BasicNameValuePair("grant_type", OAuth2Constant.OAUTH2_GRANT_TYPE_CLIENT_CREDENTIALS)); + + String scopes = String.join(" ", requestedScopes); + parameters.add(new BasicNameValuePair("scope", scopes)); + + List
headers = new ArrayList<>(); + headers.add(new BasicHeader(AUTHORIZATION_HEADER, OAuth2Constant.BASIC_HEADER + " " + + getBase64EncodedString(clientId, clientSecret))); + headers.add(new BasicHeader("Content-Type", "application/x-www-form-urlencoded")); + headers.add(new BasicHeader("User-Agent", OAuth2Constant.USER_AGENT)); + + return sendPostRequest(client, headers, parameters, + getTenantQualifiedURL(ACCESS_TOKEN_ENDPOINT, tenantInfo.getDomain())); + } + + private String createPreIssueAccessTokenAction() throws IOException { + + AuthenticationType authenticationType = new AuthenticationType(); + authenticationType.setType(AuthenticationType.TypeEnum.BASIC); + Map authProperties = new HashMap<>(); + authProperties.put(USERNAME_PROPERTY, MOCK_SERVER_AUTH_BASIC_USERNAME); + authProperties.put(PASSWORD_PROPERTY, MOCK_SERVER_AUTH_BASIC_PASSWORD); + authenticationType.setProperties(authProperties); + + Endpoint endpoint = new Endpoint(); + endpoint.setUri(EXTERNAL_SERVICE_URI); + endpoint.setAuthentication(authenticationType); + + ActionModel actionModel = new ActionModel(); + actionModel.setName("Access Token Pre Issue"); + actionModel.setDescription("This is a test pre issue access token type"); + actionModel.setEndpoint(endpoint); + + return createAction(PRE_ISSUE_ACCESS_TOKEN_API_PATH, actionModel); + } +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/PreIssueAccessTokenActionFailureCodeGrantTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/PreIssueAccessTokenActionFailureCodeGrantTestCase.java new file mode 100644 index 00000000000..80defdc50bc --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/PreIssueAccessTokenActionFailureCodeGrantTestCase.java @@ -0,0 +1,326 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.identity.integration.test.actions; + +import org.apache.http.Header; +import org.apache.http.HttpResponse; +import org.apache.http.NameValuePair; +import org.apache.http.client.utils.URLEncodedUtils; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.DefaultRedirectStrategy; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.message.BasicHeader; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; +import org.json.JSONObject; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; +import org.wso2.carbon.automation.engine.context.TestUserMode; +import org.wso2.identity.integration.test.actions.dataprovider.model.ActionResponse; +import org.wso2.identity.integration.test.actions.dataprovider.model.ExpectedTokenResponse; +import org.wso2.identity.integration.test.actions.mockserver.ActionsMockServer; +import org.wso2.identity.integration.test.oauth2.dataprovider.model.ApplicationConfig; +import org.wso2.identity.integration.test.oauth2.dataprovider.model.UserClaimConfig; +import org.wso2.identity.integration.test.rest.api.server.action.management.v1.model.ActionModel; +import org.wso2.identity.integration.test.rest.api.server.action.management.v1.model.AuthenticationType; +import org.wso2.identity.integration.test.rest.api.server.action.management.v1.model.Endpoint; +import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.ApplicationResponseModel; +import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.OpenIDConnectConfiguration; +import org.wso2.identity.integration.test.rest.api.user.common.model.Email; +import org.wso2.identity.integration.test.rest.api.user.common.model.Name; +import org.wso2.identity.integration.test.rest.api.user.common.model.UserObject; +import org.wso2.identity.integration.test.restclients.SCIM2RestClient; +import org.wso2.identity.integration.test.utils.DataExtractUtil; +import org.wso2.identity.integration.test.utils.FileUtils; +import org.wso2.identity.integration.test.utils.OAuth2Constant; + +import java.io.IOException; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.wso2.identity.integration.test.utils.OAuth2Constant.ACCESS_TOKEN_ENDPOINT; +import static org.wso2.identity.integration.test.utils.OAuth2Constant.AUTHORIZATION_HEADER; +import static org.wso2.identity.integration.test.utils.OAuth2Constant.AUTHORIZE_ENDPOINT_URL; +import static org.wso2.identity.integration.test.utils.OAuth2Constant.OAUTH2_GRANT_TYPE_AUTHORIZATION_CODE; + +/** + * This class tests the pre issue access token action failure scenarios with code grant type. + */ +public class PreIssueAccessTokenActionFailureCodeGrantTestCase extends ActionsBaseTestCase { + + private static final String USERNAME_PROPERTY = "username"; + private static final String PASSWORD_PROPERTY = "password"; + private static final String TEST_USER = "test_user"; + private static final String TEST_WSO2 = "Test@wso2"; + private static final String EXTERNAL_SERVICE_URI = "http://localhost:8587/test/action"; + private static final String PRE_ISSUE_ACCESS_TOKEN_API_PATH = "preIssueAccessToken"; + private static final String MOCK_SERVER_ENDPOINT_RESOURCE_PATH = "/test/action"; + private static final String MOCK_SERVER_AUTH_BASIC_USERNAME = "test"; + private static final String MOCK_SERVER_AUTH_BASIC_PASSWORD = "test"; + private CloseableHttpClient client; + private SCIM2RestClient scim2RestClient; + private List requestedScopes; + private String sessionDataKey; + private String authorizationCode; + private String clientId; + private String clientSecret; + private String actionId; + private String applicationId; + private String userId; + private final TestUserMode userMode; + private ActionsMockServer actionsMockServer; + private final ActionResponse actionResponse; + private final ExpectedTokenResponse expectedResponse; + + @Factory(dataProvider = "testExecutionContextProvider") + public PreIssueAccessTokenActionFailureCodeGrantTestCase(TestUserMode testUserMode, ActionResponse actionResponse, + ExpectedTokenResponse expectedResponse) { + + this.userMode = testUserMode; + this.actionResponse = actionResponse; + this.expectedResponse = expectedResponse; + } + + @DataProvider(name = "testExecutionContextProvider") + public static Object[][] getTestExecutionContext() throws Exception { + + return new Object[][]{ + {TestUserMode.SUPER_TENANT_USER, new ActionResponse(200, + FileUtils.readFileInClassPathAsString("actions/response/failure-response.json")), + new ExpectedTokenResponse(400, "Some failure reason", "Some description")}, + {TestUserMode.TENANT_USER, new ActionResponse(200, + FileUtils.readFileInClassPathAsString("actions/response/failure-response.json")), + new ExpectedTokenResponse(400, "Some failure reason", "Some description")}, + {TestUserMode.TENANT_USER, new ActionResponse(500, + FileUtils.readFileInClassPathAsString("actions/response/error-response.json")), + new ExpectedTokenResponse(500, "server_error", "Internal Server Error.")}, + {TestUserMode.TENANT_USER, new ActionResponse(401, "Unauthorized"), + new ExpectedTokenResponse(500, "server_error", "Internal Server Error.")}, + }; + } + + @BeforeClass(alwaysRun = true) + public void testInit() throws Exception { + + super.init(userMode); + client = HttpClientBuilder.create() + .setRedirectStrategy(new DefaultRedirectStrategy() { + @Override + protected boolean isRedirectable(String method) { + + return false; + } + }).build(); + + scim2RestClient = new SCIM2RestClient(serverURL, tenantInfo); + applicationId = createOIDCAppWithClaims(); + actionId = createPreIssueAccessTokenAction(); + addUser(); + + requestedScopes = new ArrayList<>(Arrays.asList("openid", "profile")); + + actionsMockServer = new ActionsMockServer(); + actionsMockServer.startServer(); + actionsMockServer.setupStub(MOCK_SERVER_ENDPOINT_RESOURCE_PATH, + "Basic " + getBase64EncodedString(MOCK_SERVER_AUTH_BASIC_USERNAME, MOCK_SERVER_AUTH_BASIC_PASSWORD), + actionResponse.getResponseBody(), actionResponse.getStatusCode()); + } + + @AfterClass(alwaysRun = true) + public void atEnd() throws Exception { + + actionsMockServer.stopServer(); + + deleteAction(PRE_ISSUE_ACCESS_TOKEN_API_PATH, actionId); + deleteApp(applicationId); + scim2RestClient.deleteUser(userId); + + restClient.closeHttpClient(); + scim2RestClient.closeHttpClient(); + actionsRestClient.closeHttpClient(); + client.close(); + + actionsMockServer = null; + authorizationCode = null; + } + + @Test(groups = "wso2.is", description = "Verify token response when pre-issue access token action fails with " + + "authorization code grant type.") + public void testPreIssueAccessActionFailure() throws Exception { + + sendAuthorizeRequest(); + performUserLogin(); + HttpResponse response = sendTokenRequestForCodeGrant(); + + assertNotNull(response); + assertEquals(response.getStatusLine().getStatusCode(), expectedResponse.getStatusCode()); + + String responseString = EntityUtils.toString(response.getEntity(), "UTF-8"); + JSONObject jsonResponse = new JSONObject(responseString); + assertEquals(jsonResponse.getString("error"), expectedResponse.getErrorMessage()); + assertEquals(jsonResponse.getString("error_description"), expectedResponse.getErrorDescription()); + } + + private void sendAuthorizeRequest() throws Exception { + + List urlParameters = new ArrayList<>(); + urlParameters.add(new BasicNameValuePair("response_type", OAuth2Constant.OAUTH2_GRANT_TYPE_CODE)); + urlParameters.add(new BasicNameValuePair("client_id", clientId)); + urlParameters.add(new BasicNameValuePair("redirect_uri", OAuth2Constant.CALLBACK_URL)); + + String scopes = String.join(" ", requestedScopes); + urlParameters.add(new BasicNameValuePair("scope", scopes)); + + HttpResponse response = sendPostRequestWithParameters(client, urlParameters, + getTenantQualifiedURL(AUTHORIZE_ENDPOINT_URL, tenantInfo.getDomain())); + + Header locationHeader = response.getFirstHeader(OAuth2Constant.HTTP_RESPONSE_HEADER_LOCATION); + assertNotNull(locationHeader, "Location header expected for authorize request is not available"); + EntityUtils.consume(response.getEntity()); + + response = sendGetRequest(client, locationHeader.getValue()); + + Map keyPositionMap = new HashMap<>(1); + keyPositionMap.put("name=\"sessionDataKey\"", 1); + List keyValues = DataExtractUtil.extractDataFromResponse(response, keyPositionMap); + assertNotNull(keyValues, "SessionDataKey key value is null"); + + sessionDataKey = keyValues.get(0).getValue(); + assertNotNull(sessionDataKey, "Session data key is null"); + EntityUtils.consume(response.getEntity()); + } + + public void performUserLogin() throws Exception { + + HttpResponse response = sendLoginPostForCustomUsers(client, sessionDataKey, TEST_USER, TEST_WSO2); + + Header locationHeader = response.getFirstHeader(OAuth2Constant.HTTP_RESPONSE_HEADER_LOCATION); + assertNotNull(locationHeader, "Location header expected post login is not available."); + EntityUtils.consume(response.getEntity()); + + response = sendGetRequest(client, locationHeader.getValue()); + locationHeader = response.getFirstHeader(OAuth2Constant.HTTP_RESPONSE_HEADER_LOCATION); + assertNotNull(locationHeader, "Redirection URL to the application with authorization code is null."); + EntityUtils.consume(response.getEntity()); + + authorizationCode = getAuthorizationCodeFromURL(locationHeader.getValue()); + assertNotNull(authorizationCode); + } + + private HttpResponse sendTokenRequestForCodeGrant() throws Exception { + + List urlParameters = new ArrayList<>(); + urlParameters.add(new BasicNameValuePair("code", authorizationCode)); + urlParameters.add(new BasicNameValuePair("grant_type", OAUTH2_GRANT_TYPE_AUTHORIZATION_CODE)); + urlParameters.add(new BasicNameValuePair("redirect_uri", OAuth2Constant.CALLBACK_URL)); + urlParameters.add(new BasicNameValuePair("client_id", clientId)); + + String scopes = String.join(" ", requestedScopes); + urlParameters.add(new BasicNameValuePair("scope", scopes)); + + List
headers = new ArrayList<>(); + headers.add(new BasicHeader(AUTHORIZATION_HEADER, + OAuth2Constant.BASIC_HEADER + " " + getBase64EncodedString(clientId, clientSecret))); + headers.add(new BasicHeader("Content-Type", "application/x-www-form-urlencoded")); + headers.add(new BasicHeader("User-Agent", OAuth2Constant.USER_AGENT)); + + return sendPostRequest(client, headers, urlParameters, + getTenantQualifiedURL(ACCESS_TOKEN_ENDPOINT, tenantInfo.getDomain())); + } + + private String getAuthorizationCodeFromURL(String location) { + + URI uri = URI.create(location); + return URLEncodedUtils.parse(uri, StandardCharsets.UTF_8).stream() + .filter(param -> "code".equals(param.getName())) + .map(NameValuePair::getValue) + .findFirst() + .orElse(null); + } + + private String createPreIssueAccessTokenAction() throws IOException { + + AuthenticationType authenticationType = new AuthenticationType(); + authenticationType.setType(AuthenticationType.TypeEnum.BASIC); + Map authProperties = new HashMap<>(); + authProperties.put(USERNAME_PROPERTY, MOCK_SERVER_AUTH_BASIC_USERNAME); + authProperties.put(PASSWORD_PROPERTY, MOCK_SERVER_AUTH_BASIC_PASSWORD); + authenticationType.setProperties(authProperties); + + Endpoint endpoint = new Endpoint(); + endpoint.setUri(EXTERNAL_SERVICE_URI); + endpoint.setAuthentication(authenticationType); + + ActionModel actionModel = new ActionModel(); + actionModel.setName("Access Token Pre Issue"); + actionModel.setDescription("This is a test pre issue access token type"); + actionModel.setEndpoint(endpoint); + + return createAction(PRE_ISSUE_ACCESS_TOKEN_API_PATH, actionModel); + } + + private void addUser() throws Exception { + + UserObject userInfo = new UserObject(); + userInfo.setUserName(TEST_USER); + userInfo.setPassword(TEST_WSO2); + userInfo.setName(new Name().givenName("test_user_given_name")); + userInfo.getName().setFamilyName("test_user_last_name"); + userInfo.addEmail(new Email().value("test.user@gmail.com")); + userId = scim2RestClient.createUser(userInfo); + } + + private String createOIDCAppWithClaims() throws Exception { + + List userClaimConfigs = Arrays.asList( + new UserClaimConfig.Builder().localClaimUri("http://wso2.org/claims/givenname"). + oidcClaimUri("given_name").build(), + new UserClaimConfig.Builder().localClaimUri("http://wso2.org/claims/lastname"). + oidcClaimUri("family_name").build() + ); + + ApplicationConfig applicationConfig = new ApplicationConfig.Builder() + .claimsList(userClaimConfigs) + .grantTypes(new ArrayList<>(Collections.singleton(OAUTH2_GRANT_TYPE_AUTHORIZATION_CODE))) + .tokenType(ApplicationConfig.TokenType.JWT) + .expiryTime(3600) + .skipConsent(true) + .build(); + + ApplicationResponseModel application = addApplication(applicationConfig); + String applicationId = application.getId(); + + OpenIDConnectConfiguration oidcConfig = getOIDCInboundDetailsOfApplication(applicationId); + clientId = oidcConfig.getClientId(); + clientSecret = oidcConfig.getClientSecret(); + + return applicationId; + } +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/PreIssueAccessTokenActionFailurePasswordGrantTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/PreIssueAccessTokenActionFailurePasswordGrantTestCase.java new file mode 100644 index 00000000000..e2ca94f144f --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/PreIssueAccessTokenActionFailurePasswordGrantTestCase.java @@ -0,0 +1,227 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.identity.integration.test.actions; + +import org.apache.http.Header; +import org.apache.http.HttpResponse; +import org.apache.http.NameValuePair; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.message.BasicHeader; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; +import org.json.JSONObject; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; +import org.wso2.carbon.automation.engine.context.TestUserMode; +import org.wso2.identity.integration.test.actions.dataprovider.model.ActionResponse; +import org.wso2.identity.integration.test.actions.dataprovider.model.ExpectedTokenResponse; +import org.wso2.identity.integration.test.actions.mockserver.ActionsMockServer; +import org.wso2.identity.integration.test.rest.api.server.action.management.v1.model.ActionModel; +import org.wso2.identity.integration.test.rest.api.server.action.management.v1.model.AuthenticationType; +import org.wso2.identity.integration.test.rest.api.server.action.management.v1.model.Endpoint; +import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.ApplicationResponseModel; +import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.OpenIDConnectConfiguration; +import org.wso2.identity.integration.test.rest.api.user.common.model.Email; +import org.wso2.identity.integration.test.rest.api.user.common.model.Name; +import org.wso2.identity.integration.test.rest.api.user.common.model.UserObject; +import org.wso2.identity.integration.test.restclients.SCIM2RestClient; +import org.wso2.identity.integration.test.utils.FileUtils; +import org.wso2.identity.integration.test.utils.OAuth2Constant; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.wso2.identity.integration.test.utils.OAuth2Constant.ACCESS_TOKEN_ENDPOINT; +import static org.wso2.identity.integration.test.utils.OAuth2Constant.AUTHORIZATION_HEADER; + +/** + * Tests the pre-issue access token action failure scenarios with password grant type. + */ +public class PreIssueAccessTokenActionFailurePasswordGrantTestCase extends ActionsBaseTestCase { + + private static final String USERNAME_PROPERTY = "username"; + private static final String PASSWORD_PROPERTY = "password"; + private static final String TEST_USER = "test_user"; + private static final String TEST_WSO2 = "Test@wso2"; + private static final String EXTERNAL_SERVICE_URI = "http://localhost:8587/test/action"; + private static final String PRE_ISSUE_ACCESS_TOKEN_API_PATH = "preIssueAccessToken"; + private static final String MOCK_SERVER_ENDPOINT_RESOURCE_PATH = "/test/action"; + private static final String MOCK_SERVER_AUTH_BASIC_USERNAME = "test"; + private static final String MOCK_SERVER_AUTH_BASIC_PASSWORD = "test"; + private static final String PASSWORD_GRANT_TYPE = "password"; + private CloseableHttpClient client; + private SCIM2RestClient scim2RestClient; + private List requestedScopes; + private String clientId; + private String clientSecret; + private String actionId; + private String applicationId; + private String userId; + private final TestUserMode userMode; + private ActionsMockServer actionsMockServer; + private final ActionResponse actionResponse; + private final ExpectedTokenResponse expectedTokenResponse; + + @Factory(dataProvider = "testExecutionContextProvider") + public PreIssueAccessTokenActionFailurePasswordGrantTestCase(TestUserMode testUserMode, + ActionResponse actionResponse, + ExpectedTokenResponse expectedTokenResponse) { + + this.userMode = testUserMode; + this.actionResponse = actionResponse; + this.expectedTokenResponse = expectedTokenResponse; + } + + @DataProvider(name = "testExecutionContextProvider") + public static Object[][] getTestExecutionContext() throws Exception { + + return new Object[][]{ + {TestUserMode.SUPER_TENANT_USER, new ActionResponse(200, + FileUtils.readFileInClassPathAsString("actions/response/failure-response.json")), + new ExpectedTokenResponse(400, "Some failure reason", "Some description")}, + {TestUserMode.TENANT_USER, new ActionResponse(200, + FileUtils.readFileInClassPathAsString("actions/response/failure-response.json")), + new ExpectedTokenResponse(400, "Some failure reason", "Some description")}, + {TestUserMode.TENANT_USER, new ActionResponse(500, + FileUtils.readFileInClassPathAsString("actions/response/error-response.json")), + new ExpectedTokenResponse(500, "server_error", "Internal Server Error.")}, + {TestUserMode.TENANT_USER, new ActionResponse(401, "Unauthorized"), + new ExpectedTokenResponse(500, "server_error", "Internal Server Error.")}, + }; + } + + @BeforeClass(alwaysRun = true) + public void testInit() throws Exception { + + super.init(userMode); + client = HttpClientBuilder.create().build(); + + scim2RestClient = new SCIM2RestClient(serverURL, tenantInfo); + ApplicationResponseModel application = addApplicationWithGrantType(PASSWORD_GRANT_TYPE); + applicationId = application.getId(); + OpenIDConnectConfiguration oidcConfig = getOIDCInboundDetailsOfApplication(applicationId); + clientId = oidcConfig.getClientId(); + clientSecret = oidcConfig.getClientSecret(); + actionId = createPreIssueAccessTokenAction(); + + addUser(); + + requestedScopes = new ArrayList<>(Arrays.asList("openid", "profile")); + + actionsMockServer = new ActionsMockServer(); + actionsMockServer.startServer(); + actionsMockServer.setupStub(MOCK_SERVER_ENDPOINT_RESOURCE_PATH, + "Basic " + getBase64EncodedString(MOCK_SERVER_AUTH_BASIC_USERNAME, MOCK_SERVER_AUTH_BASIC_PASSWORD), + actionResponse.getResponseBody(), actionResponse.getStatusCode()); + } + + @AfterClass(alwaysRun = true) + public void atEnd() throws Exception { + + actionsMockServer.stopServer(); + + deleteAction(PRE_ISSUE_ACCESS_TOKEN_API_PATH, actionId); + deleteApp(applicationId); + scim2RestClient.deleteUser(userId); + + restClient.closeHttpClient(); + scim2RestClient.closeHttpClient(); + actionsRestClient.closeHttpClient(); + client.close(); + + actionsMockServer = null; + } + + @Test(groups = "wso2.is", description = "Verify token response when pre-issue access token action fails with " + + "password grant type.") + public void testPreIssueAccessTokenActionFailure() throws Exception { + + HttpResponse response = sendTokenRequestForPasswordGrant(); + + assertNotNull(response); + assertEquals(response.getStatusLine().getStatusCode(), expectedTokenResponse.getStatusCode()); + + String responseString = EntityUtils.toString(response.getEntity(), "UTF-8"); + JSONObject jsonResponse = new JSONObject(responseString); + assertEquals(jsonResponse.getString("error"), expectedTokenResponse.getErrorMessage()); + assertEquals(jsonResponse.getString("error_description"), expectedTokenResponse.getErrorDescription()); + } + + private HttpResponse sendTokenRequestForPasswordGrant() throws Exception { + + List parameters = new ArrayList<>(); + parameters.add(new BasicNameValuePair("grant_type", OAuth2Constant.OAUTH2_GRANT_TYPE_RESOURCE_OWNER)); + parameters.add(new BasicNameValuePair("username", TEST_USER)); + parameters.add(new BasicNameValuePair("password", TEST_WSO2)); + + String scopes = String.join(" ", requestedScopes); + parameters.add(new BasicNameValuePair("scope", scopes)); + + List
headers = new ArrayList<>(); + headers.add(new BasicHeader(AUTHORIZATION_HEADER, OAuth2Constant.BASIC_HEADER + " " + + getBase64EncodedString(clientId, clientSecret))); + headers.add(new BasicHeader("Content-Type", "application/x-www-form-urlencoded")); + headers.add(new BasicHeader("User-Agent", OAuth2Constant.USER_AGENT)); + + return sendPostRequest(client, headers, parameters, + getTenantQualifiedURL(ACCESS_TOKEN_ENDPOINT, tenantInfo.getDomain())); + } + + private String createPreIssueAccessTokenAction() throws IOException { + + AuthenticationType authenticationType = new AuthenticationType(); + authenticationType.setType(AuthenticationType.TypeEnum.BASIC); + Map authProperties = new HashMap<>(); + authProperties.put(USERNAME_PROPERTY, MOCK_SERVER_AUTH_BASIC_USERNAME); + authProperties.put(PASSWORD_PROPERTY, MOCK_SERVER_AUTH_BASIC_PASSWORD); + authenticationType.setProperties(authProperties); + + Endpoint endpoint = new Endpoint(); + endpoint.setUri(EXTERNAL_SERVICE_URI); + endpoint.setAuthentication(authenticationType); + + ActionModel actionModel = new ActionModel(); + actionModel.setName("Access Token Pre Issue"); + actionModel.setDescription("This is a test pre issue access token type"); + actionModel.setEndpoint(endpoint); + + return createAction(PRE_ISSUE_ACCESS_TOKEN_API_PATH, actionModel); + } + + private void addUser() throws Exception { + + UserObject userInfo = new UserObject(); + userInfo.setUserName(TEST_USER); + userInfo.setPassword(TEST_WSO2); + userInfo.setName(new Name().givenName("test_user_given_name")); + userInfo.getName().setFamilyName("test_user_last_name"); + userInfo.addEmail(new Email().value("test.user@gmail.com")); + userId = scim2RestClient.createUser(userInfo); + } +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/PreIssueAccessTokenActionFailureRefreshTokenGrantTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/PreIssueAccessTokenActionFailureRefreshTokenGrantTestCase.java new file mode 100644 index 00000000000..56f2c235489 --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/PreIssueAccessTokenActionFailureRefreshTokenGrantTestCase.java @@ -0,0 +1,387 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.identity.integration.test.actions; + +import org.apache.http.Header; +import org.apache.http.HttpResponse; +import org.apache.http.NameValuePair; +import org.apache.http.client.utils.URLEncodedUtils; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.DefaultRedirectStrategy; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.message.BasicHeader; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; +import org.json.JSONObject; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; +import org.wso2.carbon.automation.engine.context.TestUserMode; +import org.wso2.identity.integration.test.actions.dataprovider.model.ActionResponse; +import org.wso2.identity.integration.test.actions.dataprovider.model.ExpectedTokenResponse; +import org.wso2.identity.integration.test.actions.mockserver.ActionsMockServer; +import org.wso2.identity.integration.test.oauth2.dataprovider.model.ApplicationConfig; +import org.wso2.identity.integration.test.oauth2.dataprovider.model.UserClaimConfig; +import org.wso2.identity.integration.test.rest.api.server.action.management.v1.model.ActionModel; +import org.wso2.identity.integration.test.rest.api.server.action.management.v1.model.AuthenticationType; +import org.wso2.identity.integration.test.rest.api.server.action.management.v1.model.Endpoint; +import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.ApplicationResponseModel; +import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.OpenIDConnectConfiguration; +import org.wso2.identity.integration.test.rest.api.user.common.model.Email; +import org.wso2.identity.integration.test.rest.api.user.common.model.Name; +import org.wso2.identity.integration.test.rest.api.user.common.model.UserObject; +import org.wso2.identity.integration.test.restclients.SCIM2RestClient; +import org.wso2.identity.integration.test.utils.DataExtractUtil; +import org.wso2.identity.integration.test.utils.FileUtils; +import org.wso2.identity.integration.test.utils.OAuth2Constant; + +import java.io.IOException; +import java.lang.reflect.Method; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; +import static org.wso2.identity.integration.test.utils.OAuth2Constant.ACCESS_TOKEN_ENDPOINT; +import static org.wso2.identity.integration.test.utils.OAuth2Constant.AUTHORIZATION_HEADER; +import static org.wso2.identity.integration.test.utils.OAuth2Constant.AUTHORIZE_ENDPOINT_URL; +import static org.wso2.identity.integration.test.utils.OAuth2Constant.OAUTH2_GRANT_TYPE_AUTHORIZATION_CODE; + +/** + * Tests the pre-issue access token action success scenarios with refresh token grant type. + */ +public class PreIssueAccessTokenActionFailureRefreshTokenGrantTestCase extends ActionsBaseTestCase { + + private static final String USERNAME_PROPERTY = "username"; + private static final String PASSWORD_PROPERTY = "password"; + private static final String TEST_USER = "test_user"; + private static final String TEST_WSO2 = "Test@wso2"; + private static final String EXTERNAL_SERVICE_URI = "http://localhost:8587/test/action"; + private static final String PRE_ISSUE_ACCESS_TOKEN_API_PATH = "preIssueAccessToken"; + private static final String MOCK_SERVER_ENDPOINT_RESOURCE_PATH = "/test/action"; + private static final String MOCK_SERVER_AUTH_BASIC_USERNAME = "test"; + private static final String MOCK_SERVER_AUTH_BASIC_PASSWORD = "test"; + private static final int APP_CONFIGURED_EXPIRY_TIME = 3600; + private CloseableHttpClient client; + private SCIM2RestClient scim2RestClient; + private List requestedScopes; + private String sessionDataKey; + private String authorizationCode; + private String clientId; + private String clientSecret; + private String actionId; + private String applicationId; + private String userId; + private String refreshToken; + private final TestUserMode userMode; + private final ActionResponse actionResponse; + private final ExpectedTokenResponse expectedResponse; + private ActionsMockServer actionsMockServer; + + @Factory(dataProvider = "testExecutionContextProvider") + public PreIssueAccessTokenActionFailureRefreshTokenGrantTestCase(TestUserMode testUserMode, + ActionResponse actionResponse, + ExpectedTokenResponse expectedResponse) { + + this.userMode = testUserMode; + this.actionResponse = actionResponse; + this.expectedResponse = expectedResponse; + } + + @DataProvider(name = "testExecutionContextProvider") + public static Object[][] getTestExecutionContext() throws Exception { + + return new Object[][]{ + {TestUserMode.SUPER_TENANT_USER, new ActionResponse(200, + FileUtils.readFileInClassPathAsString("actions/response/failure-response.json")), + new ExpectedTokenResponse(400, "Some failure reason", "Some description")}, + {TestUserMode.TENANT_USER, new ActionResponse(200, + FileUtils.readFileInClassPathAsString("actions/response/failure-response.json")), + new ExpectedTokenResponse(400, "Some failure reason", "Some description")}, + {TestUserMode.TENANT_USER, new ActionResponse(500, + FileUtils.readFileInClassPathAsString("actions/response/error-response.json")), + new ExpectedTokenResponse(500, "server_error", "Internal Server Error.")}, + {TestUserMode.TENANT_USER, new ActionResponse(401, "Unauthorized"), + new ExpectedTokenResponse(500, "server_error", "Internal Server Error.")}, + }; + } + + @BeforeClass(alwaysRun = true) + public void testInit() throws Exception { + + super.init(userMode); + client = HttpClientBuilder.create() + .setRedirectStrategy(new DefaultRedirectStrategy() { + @Override + protected boolean isRedirectable(String method) { + + return false; + } + }).build(); + + scim2RestClient = new SCIM2RestClient(serverURL, tenantInfo); + applicationId = createOIDCAppWithClaims(); + actionId = createPreIssueAccessTokenAction(); + addUser(); + + requestedScopes = new ArrayList<>(Arrays.asList("openid", "profile")); + + actionsMockServer = new ActionsMockServer(); + actionsMockServer.startServer(); + } + + @AfterClass(alwaysRun = true) + public void atEnd() throws Exception { + + actionsMockServer.stopServer(); + + deleteAction(PRE_ISSUE_ACCESS_TOKEN_API_PATH, actionId); + deleteApp(applicationId); + scim2RestClient.deleteUser(userId); + + restClient.closeHttpClient(); + scim2RestClient.closeHttpClient(); + actionsRestClient.closeHttpClient(); + client.close(); + + actionsMockServer = null; + authorizationCode = null; + } + + @BeforeMethod + public void setupMockServerStub(Method method) throws Exception { + + if (method.getName().equals("testGetAccessTokenWithCodeGrant")) { + actionsMockServer.setupStub(MOCK_SERVER_ENDPOINT_RESOURCE_PATH, + "Basic " + getBase64EncodedString(MOCK_SERVER_AUTH_BASIC_USERNAME, MOCK_SERVER_AUTH_BASIC_PASSWORD), + FileUtils.readFileInClassPathAsString( + "actions/response/pre-issue-access-token-response-code-before-refresh.json"), 200); + } else if (method.getName().equals("testPreIssueAccessTokenActionFailureForRefreshGrant")) { + actionsMockServer.setupStub(MOCK_SERVER_ENDPOINT_RESOURCE_PATH, + "Basic " + getBase64EncodedString(MOCK_SERVER_AUTH_BASIC_USERNAME, MOCK_SERVER_AUTH_BASIC_PASSWORD), + actionResponse.getResponseBody(), actionResponse.getStatusCode()); + } + } + + @Test(groups = "wso2.is", description = + "Get access token with authorization code grant when pre-issue access token action is successful") + public void testGetAccessTokenWithCodeGrant() throws Exception { + + sendAuthorizeRequest(); + performUserLogin(); + HttpResponse response = sendTokenRequestForCodeGrant(); + + String responseString = EntityUtils.toString(response.getEntity(), "UTF-8"); + JSONObject jsonResponse = new JSONObject(responseString); + + assertTrue(jsonResponse.has("access_token"), "Access token not found in the token response."); + assertTrue(jsonResponse.has("refresh_token"), "Refresh token not found in the token response."); + assertTrue(jsonResponse.has("expires_in"), "Expiry time not found in the token response."); + assertTrue(jsonResponse.has("token_type"), "Token type not found in the token response."); + + String accessToken = jsonResponse.getString("access_token"); + assertNotNull(accessToken, "Access token is null."); + + refreshToken = jsonResponse.getString("refresh_token"); + assertNotNull(refreshToken, "Refresh token is null."); + + int expiresIn = jsonResponse.getInt("expires_in"); + assertEquals(expiresIn, APP_CONFIGURED_EXPIRY_TIME, "Invalid expiry time for the access token."); + + String tokenType = jsonResponse.getString("token_type"); + assertEquals(tokenType, "Bearer", "Invalid token type for the access token."); + } + + @Test(groups = "wso2.is", description = + "Get access token from refresh token when pre-issue access token action is successful", + dependsOnMethods = "testGetAccessTokenWithCodeGrant") + public void testPreIssueAccessTokenActionFailureForRefreshGrant() throws Exception { + + HttpResponse response = sendTokenRequestForRefreshGrant(); + assertNotNull(response); + assertEquals(response.getStatusLine().getStatusCode(), expectedResponse.getStatusCode()); + + String responseString = EntityUtils.toString(response.getEntity(), "UTF-8"); + JSONObject jsonResponse = new JSONObject(responseString); + assertEquals(jsonResponse.getString("error"), expectedResponse.getErrorMessage()); + assertEquals(jsonResponse.getString("error_description"), expectedResponse.getErrorDescription()); + } + + private HttpResponse sendTokenRequestForRefreshGrant() throws IOException { + + List parameters = new ArrayList<>(); + parameters.add(new BasicNameValuePair("grant_type", OAuth2Constant.OAUTH2_GRANT_TYPE_REFRESH_TOKEN)); + parameters.add(new BasicNameValuePair(OAuth2Constant.OAUTH2_GRANT_TYPE_REFRESH_TOKEN, refreshToken)); + + List
headers = new ArrayList<>(); + headers.add(new BasicHeader(AUTHORIZATION_HEADER, + OAuth2Constant.BASIC_HEADER + " " + getBase64EncodedString(clientId, clientSecret))); + headers.add(new BasicHeader("Content-Type", "application/x-www-form-urlencoded")); + headers.add(new BasicHeader("User-Agent", OAuth2Constant.USER_AGENT)); + + return sendPostRequest(client, headers, parameters, + getTenantQualifiedURL(ACCESS_TOKEN_ENDPOINT, tenantInfo.getDomain())); + } + + private void sendAuthorizeRequest() throws Exception { + + List urlParameters = new ArrayList<>(); + urlParameters.add(new BasicNameValuePair("response_type", OAuth2Constant.OAUTH2_GRANT_TYPE_CODE)); + urlParameters.add(new BasicNameValuePair("client_id", clientId)); + urlParameters.add(new BasicNameValuePair("redirect_uri", OAuth2Constant.CALLBACK_URL)); + + String scopes = String.join(" ", requestedScopes); + urlParameters.add(new BasicNameValuePair("scope", scopes)); + + HttpResponse response = sendPostRequestWithParameters(client, urlParameters, + getTenantQualifiedURL(AUTHORIZE_ENDPOINT_URL, tenantInfo.getDomain())); + + Header locationHeader = response.getFirstHeader(OAuth2Constant.HTTP_RESPONSE_HEADER_LOCATION); + assertNotNull(locationHeader, "Location header expected for authorize request is not available"); + EntityUtils.consume(response.getEntity()); + + response = sendGetRequest(client, locationHeader.getValue()); + + Map keyPositionMap = new HashMap<>(1); + keyPositionMap.put("name=\"sessionDataKey\"", 1); + List keyValues = + DataExtractUtil.extractDataFromResponse(response, keyPositionMap); + assertNotNull(keyValues, "SessionDataKey key value is null"); + + sessionDataKey = keyValues.get(0).getValue(); + assertNotNull(sessionDataKey, "Session data key is null"); + EntityUtils.consume(response.getEntity()); + } + + public void performUserLogin() throws Exception { + + HttpResponse response = sendLoginPostForCustomUsers(client, sessionDataKey, TEST_USER, TEST_WSO2); + + Header locationHeader = response.getFirstHeader(OAuth2Constant.HTTP_RESPONSE_HEADER_LOCATION); + assertNotNull(locationHeader, "Location header expected post login is not available."); + EntityUtils.consume(response.getEntity()); + + response = sendGetRequest(client, locationHeader.getValue()); + locationHeader = response.getFirstHeader(OAuth2Constant.HTTP_RESPONSE_HEADER_LOCATION); + assertNotNull(locationHeader, "Redirection URL to the application with authorization code is null."); + EntityUtils.consume(response.getEntity()); + + authorizationCode = getAuthorizationCodeFromURL(locationHeader.getValue()); + assertNotNull(authorizationCode); + } + + private HttpResponse sendTokenRequestForCodeGrant() throws Exception { + + List urlParameters = new ArrayList<>(); + urlParameters.add(new BasicNameValuePair("code", authorizationCode)); + urlParameters.add(new BasicNameValuePair("grant_type", OAUTH2_GRANT_TYPE_AUTHORIZATION_CODE)); + urlParameters.add(new BasicNameValuePair("redirect_uri", OAuth2Constant.CALLBACK_URL)); + urlParameters.add(new BasicNameValuePair("client_id", clientId)); + + String scopes = String.join(" ", requestedScopes); + urlParameters.add(new BasicNameValuePair("scope", scopes)); + + List
headers = new ArrayList<>(); + headers.add(new BasicHeader(AUTHORIZATION_HEADER, + OAuth2Constant.BASIC_HEADER + " " + getBase64EncodedString(clientId, clientSecret))); + headers.add(new BasicHeader("Content-Type", "application/x-www-form-urlencoded")); + headers.add(new BasicHeader("User-Agent", OAuth2Constant.USER_AGENT)); + + return sendPostRequest(client, headers, urlParameters, + getTenantQualifiedURL(ACCESS_TOKEN_ENDPOINT, tenantInfo.getDomain())); + } + + private String getAuthorizationCodeFromURL(String location) { + + URI uri = URI.create(location); + return URLEncodedUtils.parse(uri, StandardCharsets.UTF_8).stream() + .filter(param -> "code".equals(param.getName())) + .map(NameValuePair::getValue) + .findFirst() + .orElse(null); + } + + private String createPreIssueAccessTokenAction() throws IOException { + + AuthenticationType authenticationType = new AuthenticationType(); + authenticationType.setType(AuthenticationType.TypeEnum.BASIC); + Map authProperties = new HashMap<>(); + authProperties.put(USERNAME_PROPERTY, MOCK_SERVER_AUTH_BASIC_USERNAME); + authProperties.put(PASSWORD_PROPERTY, MOCK_SERVER_AUTH_BASIC_PASSWORD); + authenticationType.setProperties(authProperties); + + Endpoint endpoint = new Endpoint(); + endpoint.setUri(EXTERNAL_SERVICE_URI); + endpoint.setAuthentication(authenticationType); + + ActionModel actionModel = new ActionModel(); + actionModel.setName("Access Token Pre Issue"); + actionModel.setDescription("This is a test pre issue access token type"); + actionModel.setEndpoint(endpoint); + + return createAction(PRE_ISSUE_ACCESS_TOKEN_API_PATH, actionModel); + } + + private void addUser() throws Exception { + + UserObject userInfo = new UserObject(); + userInfo.setUserName(TEST_USER); + userInfo.setPassword(TEST_WSO2); + userInfo.setName(new Name().givenName("test_user_given_name")); + userInfo.getName().setFamilyName("test_user_last_name"); + userInfo.addEmail(new Email().value("test.user@gmail.com")); + userId = scim2RestClient.createUser(userInfo); + } + + private String createOIDCAppWithClaims() throws Exception { + + List userClaimConfigs = Arrays.asList( + new UserClaimConfig.Builder().localClaimUri("http://wso2.org/claims/givenname"). + oidcClaimUri("given_name").build(), + new UserClaimConfig.Builder().localClaimUri("http://wso2.org/claims/lastname"). + oidcClaimUri("family_name").build() + ); + + ApplicationConfig applicationConfig = new ApplicationConfig.Builder() + .claimsList(userClaimConfigs) + .grantTypes(new ArrayList<>(Arrays.asList("authorization_code", "refresh_token"))) + .tokenType(ApplicationConfig.TokenType.JWT) + .expiryTime(APP_CONFIGURED_EXPIRY_TIME) + .skipConsent(true) + .build(); + + ApplicationResponseModel application = addApplication(applicationConfig); + String applicationIdentifier = application.getId(); + + OpenIDConnectConfiguration oidcConfig = getOIDCInboundDetailsOfApplication(applicationIdentifier); + clientId = oidcConfig.getClientId(); + clientSecret = oidcConfig.getClientSecret(); + + return applicationIdentifier; + } +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/PreIssueAccessTokenClientCredentialsGrantTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/PreIssueAccessTokenActionSuccessClientCredentialsGrantTestCase.java similarity index 99% rename from modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/PreIssueAccessTokenClientCredentialsGrantTestCase.java rename to modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/PreIssueAccessTokenActionSuccessClientCredentialsGrantTestCase.java index b9803ae552a..5a65ef702d8 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/PreIssueAccessTokenClientCredentialsGrantTestCase.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/PreIssueAccessTokenActionSuccessClientCredentialsGrantTestCase.java @@ -86,7 +86,7 @@ * This test case extends {@link ActionsBaseTestCase} and focuses on scenarios related * to scopes and claims modifications through an external service. */ -public class PreIssueAccessTokenClientCredentialsGrantTestCase extends ActionsBaseTestCase { +public class PreIssueAccessTokenActionSuccessClientCredentialsGrantTestCase extends ActionsBaseTestCase { private static final String USERNAME_PROPERTY = "username"; private static final String PASSWORD_PROPERTY = "password"; @@ -137,7 +137,7 @@ public class PreIssueAccessTokenClientCredentialsGrantTestCase extends ActionsBa private ActionsMockServer actionsMockServer; @Factory(dataProvider = "testExecutionContextProvider") - public PreIssueAccessTokenClientCredentialsGrantTestCase(TestUserMode testUserMode) { + public PreIssueAccessTokenActionSuccessClientCredentialsGrantTestCase(TestUserMode testUserMode) { this.userMode = testUserMode; this.tenantId = testUserMode == TestUserMode.SUPER_TENANT_USER ? "-1234" : "1"; diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/PreIssueAccessTokenCodeGrantTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/PreIssueAccessTokenActionSuccessCodeGrantTestCase.java similarity index 99% rename from modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/PreIssueAccessTokenCodeGrantTestCase.java rename to modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/PreIssueAccessTokenActionSuccessCodeGrantTestCase.java index ca71adf6743..1e6041e4b5e 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/PreIssueAccessTokenCodeGrantTestCase.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/PreIssueAccessTokenActionSuccessCodeGrantTestCase.java @@ -59,7 +59,6 @@ import org.wso2.identity.integration.test.actions.model.User; import org.wso2.identity.integration.test.actions.model.UserStore; import org.wso2.identity.integration.test.oauth2.dataprovider.model.ApplicationConfig; -import org.wso2.identity.integration.test.oauth2.dataprovider.model.TokenScopes; import org.wso2.identity.integration.test.oauth2.dataprovider.model.UserClaimConfig; import org.wso2.identity.integration.test.rest.api.server.action.management.v1.model.ActionModel; import org.wso2.identity.integration.test.rest.api.server.action.management.v1.model.AuthenticationType; @@ -107,7 +106,7 @@ * This test case extends {@link ActionsBaseTestCase} and focuses on scenarios related * to scopes and claims modifications through an external service. */ -public class PreIssueAccessTokenCodeGrantTestCase extends ActionsBaseTestCase { +public class PreIssueAccessTokenActionSuccessCodeGrantTestCase extends ActionsBaseTestCase { private static final String USERS = "users"; private static final String USERNAME_PROPERTY = "username"; @@ -171,7 +170,7 @@ public class PreIssueAccessTokenCodeGrantTestCase extends ActionsBaseTestCase { private ActionsMockServer actionsMockServer; @Factory(dataProvider = "testExecutionContextProvider") - public PreIssueAccessTokenCodeGrantTestCase(TestUserMode testUserMode) { + public PreIssueAccessTokenActionSuccessCodeGrantTestCase(TestUserMode testUserMode) { this.userMode = testUserMode; this.tenantId = testUserMode == TestUserMode.SUPER_TENANT_USER ? "-1234" : "1"; diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/PreIssueAccessTokenPasswordGrantTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/PreIssueAccessTokenActionSuccessPasswordGrantTestCase.java similarity index 99% rename from modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/PreIssueAccessTokenPasswordGrantTestCase.java rename to modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/PreIssueAccessTokenActionSuccessPasswordGrantTestCase.java index c030bfcb708..146c7733255 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/PreIssueAccessTokenPasswordGrantTestCase.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/PreIssueAccessTokenActionSuccessPasswordGrantTestCase.java @@ -99,7 +99,7 @@ * This test case extends {@link ActionsBaseTestCase} and focuses on scenarios related * to scopes and claims modifications through an external service. */ -public class PreIssueAccessTokenPasswordGrantTestCase extends ActionsBaseTestCase { +public class PreIssueAccessTokenActionSuccessPasswordGrantTestCase extends ActionsBaseTestCase { private static final String USERS = "users"; private static final String USERNAME_PROPERTY = "username"; @@ -158,7 +158,7 @@ public class PreIssueAccessTokenPasswordGrantTestCase extends ActionsBaseTestCas private ActionsMockServer actionsMockServer; @Factory(dataProvider = "testExecutionContextProvider") - public PreIssueAccessTokenPasswordGrantTestCase(TestUserMode testUserMode) { + public PreIssueAccessTokenActionSuccessPasswordGrantTestCase(TestUserMode testUserMode) { this.userMode = testUserMode; this.tenantId = testUserMode == TestUserMode.SUPER_TENANT_USER ? "-1234" : "1"; diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/PreIssueAccessTokenActionSuccessRefreshTokenGrantTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/PreIssueAccessTokenActionSuccessRefreshTokenGrantTestCase.java new file mode 100644 index 00000000000..354bc794b87 --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/PreIssueAccessTokenActionSuccessRefreshTokenGrantTestCase.java @@ -0,0 +1,501 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.identity.integration.test.actions; + +import com.nimbusds.jwt.JWTClaimsSet; +import com.nimbusds.jwt.SignedJWT; +import org.apache.commons.lang.ArrayUtils; +import org.apache.http.Header; +import org.apache.http.HttpResponse; +import org.apache.http.NameValuePair; +import org.apache.http.client.utils.URLEncodedUtils; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.DefaultRedirectStrategy; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.message.BasicHeader; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; +import org.json.JSONObject; +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; +import org.wso2.carbon.automation.engine.context.TestUserMode; +import org.wso2.identity.integration.test.actions.mockserver.ActionsMockServer; +import org.wso2.identity.integration.test.oauth2.dataprovider.model.ApplicationConfig; +import org.wso2.identity.integration.test.oauth2.dataprovider.model.UserClaimConfig; +import org.wso2.identity.integration.test.rest.api.server.action.management.v1.model.ActionModel; +import org.wso2.identity.integration.test.rest.api.server.action.management.v1.model.AuthenticationType; +import org.wso2.identity.integration.test.rest.api.server.action.management.v1.model.Endpoint; +import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.ApplicationResponseModel; +import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.OpenIDConnectConfiguration; +import org.wso2.identity.integration.test.rest.api.user.common.model.Email; +import org.wso2.identity.integration.test.rest.api.user.common.model.Name; +import org.wso2.identity.integration.test.rest.api.user.common.model.UserObject; +import org.wso2.identity.integration.test.restclients.SCIM2RestClient; +import org.wso2.identity.integration.test.utils.DataExtractUtil; +import org.wso2.identity.integration.test.utils.FileUtils; +import org.wso2.identity.integration.test.utils.OAuth2Constant; + +import java.io.IOException; +import java.lang.reflect.Method; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; +import static org.wso2.identity.integration.test.utils.OAuth2Constant.ACCESS_TOKEN_ENDPOINT; +import static org.wso2.identity.integration.test.utils.OAuth2Constant.AUTHORIZATION_HEADER; +import static org.wso2.identity.integration.test.utils.OAuth2Constant.AUTHORIZE_ENDPOINT_URL; +import static org.wso2.identity.integration.test.utils.OAuth2Constant.OAUTH2_GRANT_TYPE_AUTHORIZATION_CODE; + +/** + * Tests the pre-issue access token action success scenarios with refresh token grant type. + */ +public class PreIssueAccessTokenActionSuccessRefreshTokenGrantTestCase extends ActionsBaseTestCase { + + private static final String USERNAME_PROPERTY = "username"; + private static final String PASSWORD_PROPERTY = "password"; + private static final String TEST_USER = "test_user"; + private static final String TEST_WSO2 = "Test@wso2"; + private static final String EXTERNAL_SERVICE_URI = "http://localhost:8587/test/action"; + private static final String PRE_ISSUE_ACCESS_TOKEN_API_PATH = "preIssueAccessToken"; + private static final String MOCK_SERVER_ENDPOINT_RESOURCE_PATH = "/test/action"; + private static final String MOCK_SERVER_AUTH_BASIC_USERNAME = "test"; + private static final String MOCK_SERVER_AUTH_BASIC_PASSWORD = "test"; + private static final int APP_CONFIGURED_EXPIRY_TIME = 3600; + private static final int UPDATED_EXPIRY_TIME_BY_ACTION = 7200; + private CloseableHttpClient client; + private SCIM2RestClient scim2RestClient; + private List requestedScopes; + private String sessionDataKey; + private String authorizationCode; + private String clientId; + private String clientSecret; + private String actionId; + private String applicationId; + private String userId; + private String accessToken; + private String refreshToken; + private JWTClaimsSet accessTokenClaims; + private final TestUserMode userMode; + private ActionsMockServer actionsMockServer; + + @Factory(dataProvider = "testExecutionContextProvider") + public PreIssueAccessTokenActionSuccessRefreshTokenGrantTestCase(TestUserMode testUserMode) { + + this.userMode = testUserMode; + } + + @DataProvider(name = "testExecutionContextProvider") + public static Object[][] getTestExecutionContext() { + + return new Object[][]{ + {TestUserMode.SUPER_TENANT_USER}, + {TestUserMode.TENANT_USER} + }; + } + + @BeforeClass(alwaysRun = true) + public void testInit() throws Exception { + + super.init(userMode); + client = HttpClientBuilder.create() + .setRedirectStrategy(new DefaultRedirectStrategy() { + @Override + protected boolean isRedirectable(String method) { + + return false; + } + }).build(); + + scim2RestClient = new SCIM2RestClient(serverURL, tenantInfo); + applicationId = createOIDCAppWithClaims(); + actionId = createPreIssueAccessTokenAction(); + addUser(); + + requestedScopes = new ArrayList<>(Arrays.asList("openid", "profile")); + + actionsMockServer = new ActionsMockServer(); + actionsMockServer.startServer(); + } + + @AfterClass(alwaysRun = true) + public void atEnd() throws Exception { + + actionsMockServer.stopServer(); + + deleteAction(PRE_ISSUE_ACCESS_TOKEN_API_PATH, actionId); + deleteApp(applicationId); + scim2RestClient.deleteUser(userId); + + restClient.closeHttpClient(); + scim2RestClient.closeHttpClient(); + actionsRestClient.closeHttpClient(); + client.close(); + + actionsMockServer = null; + authorizationCode = null; + } + + @BeforeMethod + public void setupMockServerStub(Method method) throws Exception { + + if (method.getName().equals("testGetAccessTokenWithCodeGrant")) { + actionsMockServer.setupStub(MOCK_SERVER_ENDPOINT_RESOURCE_PATH, + "Basic " + getBase64EncodedString(MOCK_SERVER_AUTH_BASIC_USERNAME, MOCK_SERVER_AUTH_BASIC_PASSWORD), + FileUtils.readFileInClassPathAsString( + "actions/response/pre-issue-access-token-response-code-before-refresh.json"), 200); + } else if (method.getName().equals("testGetAccessTokenFromRefreshToken")) { + actionsMockServer.setupStub(MOCK_SERVER_ENDPOINT_RESOURCE_PATH, + "Basic " + getBase64EncodedString(MOCK_SERVER_AUTH_BASIC_USERNAME, MOCK_SERVER_AUTH_BASIC_PASSWORD), + FileUtils.readFileInClassPathAsString("actions/response/pre-issue-access-token-response.json"), + 200); + } + } + + @Test(groups = "wso2.is", description = + "Get access token with authorization code grant when pre-issue access token action is successful") + public void testGetAccessTokenWithCodeGrant() throws Exception { + + sendAuthorizeRequest(); + performUserLogin(); + HttpResponse response = sendTokenRequestForCodeGrant(); + + String responseString = EntityUtils.toString(response.getEntity(), "UTF-8"); + JSONObject jsonResponse = new JSONObject(responseString); + + assertTrue(jsonResponse.has("access_token"), "Access token not found in the token response."); + assertTrue(jsonResponse.has("refresh_token"), "Refresh token not found in the token response."); + assertTrue(jsonResponse.has("expires_in"), "Expiry time not found in the token response."); + assertTrue(jsonResponse.has("token_type"), "Token type not found in the token response."); + + accessToken = jsonResponse.getString("access_token"); + assertNotNull(accessToken, "Access token is null."); + + refreshToken = jsonResponse.getString("refresh_token"); + assertNotNull(refreshToken, "Refresh token is null."); + + int expiresIn = jsonResponse.getInt("expires_in"); + assertEquals(expiresIn, APP_CONFIGURED_EXPIRY_TIME, "Invalid expiry time for the access token."); + + String tokenType = jsonResponse.getString("token_type"); + assertEquals(tokenType, "Bearer", "Invalid token type for the access token."); + + accessTokenClaims = getJWTClaimSetFromToken(accessToken); + assertNotNull(accessTokenClaims); + } + + @Test(groups = "wso2.is", description = "Verify the custom string claim in the access token added by action", + dependsOnMethods = "testGetAccessTokenWithCodeGrant") + public void testClaimAddOperationFromPreIssueAccessTokenActionForCodeGrant() throws Exception { + + String claimValue = accessTokenClaims.getStringClaim("custom_claim_string_0"); + Assert.assertEquals(claimValue, "testCustomClaim0"); + } + + @Test(groups = "wso2.is", description = + "Get access token from refresh token when pre-issue access token action is successful", + dependsOnMethods = "testGetAccessTokenWithCodeGrant") + public void testGetAccessTokenFromRefreshToken() throws Exception { + + HttpResponse response = sendTokenRequestForRefreshGrant(); + + String responseString = EntityUtils.toString(response.getEntity(), "UTF-8"); + JSONObject jsonResponse = new JSONObject(responseString); + + assertTrue(jsonResponse.has("access_token"), "Access token not found in the token response."); + assertTrue(jsonResponse.has("refresh_token"), "Refresh token not found in the token response."); + assertTrue(jsonResponse.has("expires_in"), "Expiry time not found in the token response."); + assertTrue(jsonResponse.has("token_type"), "Token type not found in the token response."); + + accessToken = jsonResponse.getString("access_token"); + assertNotNull(accessToken, "Access token is null."); + + refreshToken = jsonResponse.getString("refresh_token"); + assertNotNull(refreshToken, "Refresh token is null."); + + int expiresIn = jsonResponse.getInt("expires_in"); + assertEquals(expiresIn, UPDATED_EXPIRY_TIME_BY_ACTION, "Invalid expiry time for the access token."); + + String tokenType = jsonResponse.getString("token_type"); + assertEquals(tokenType, "Bearer", "Invalid token type for the access token."); + + accessTokenClaims = getJWTClaimSetFromToken(accessToken); + assertNotNull(accessTokenClaims); + } + + @Test(groups = "wso2.is", description = "Verify the custom string claim added by action in " + + "code grant is available in the access token", dependsOnMethods = "testGetAccessTokenFromRefreshToken") + public void testClaimAddForAccessTokenFromPreIssueAccessTokenActionForRefreshTokenGrant() + throws Exception { + + testClaimAddOperationFromPreIssueAccessTokenActionForCodeGrant(); + } + + @Test(groups = "wso2.is", description = "Verify the custom boolean claim added by action in the access token", + dependsOnMethods = "testGetAccessTokenFromRefreshToken") + public void testBooleanClaimAddOperationFromPreIssueAccessTokenActionForRefreshTokenGrant() throws Exception { + + boolean claimValue = accessTokenClaims.getBooleanClaim("custom_claim_boolean_1"); + Assert.assertTrue(claimValue); + } + + @Test(groups = "wso2.is", description = "Verify the custom string claim added by action in the access token", + dependsOnMethods = "testGetAccessTokenFromRefreshToken") + public void testStringClaimAddOperationFromPreIssueAccessTokenActionForRefreshTokenGrant() throws Exception { + + String claimValue = accessTokenClaims.getStringClaim("custom_claim_string_1"); + Assert.assertEquals(claimValue, "testCustomClaim1"); + } + + @Test(groups = "wso2.is", description = "Verify the custom number claim added by action in the access token", + dependsOnMethods = "testGetAccessTokenFromRefreshToken") + public void testNumberClaimAddOperationFromPreIssueAccessTokenActionForRefreshTokenGrant() throws Exception { + + int claimValue = accessTokenClaims.getIntegerClaim("custom_claim_number_1"); + Assert.assertEquals(claimValue, 78); + } + + @Test(groups = "wso2.is", description = "Verify the custom string array claim added by action in the " + + "access token", dependsOnMethods = "testGetAccessTokenFromRefreshToken") + public void testClaimArrayAddOperationFromPreIssueAccessTokenActionForRefreshTokenGrant() + throws Exception { + + String[] expectedClaimArrayInToken = {"TestCustomClaim1", "TestCustomClaim2", "TestCustomClaim3"}; + + String[] addedClaimArrayToToken = accessTokenClaims.getStringArrayClaim("custom_claim_string_array_1"); + Assert.assertEquals(addedClaimArrayToToken, expectedClaimArrayInToken); + } + + @Test(groups = "wso2.is", description = "Verify the given_name claim replaced by the action in " + + "access token", dependsOnMethods = "testGetAccessTokenFromRefreshToken") + public void testGivenNameReplaceOperationFromPreIssueAccessTokenActionForRefreshTokenGrant() + throws Exception { + + String givenNameClaim = accessTokenClaims.getStringClaim("given_name"); + Assert.assertEquals(givenNameClaim, "replaced_given_name"); + } + + @Test(groups = "wso2.is", description = "Verify the 'aud' claim updated by action in the " + + "access token", dependsOnMethods = "testGetAccessTokenFromRefreshToken") + public void testAUDUpdateOperationsFromPreIssueAccessTokenActionForRefreshTokenGrant() throws Exception { + + String[] audValueArray = accessTokenClaims.getStringArrayClaim("aud"); + + Assert.assertTrue(ArrayUtils.contains(audValueArray, "zzz1.com")); + Assert.assertTrue(ArrayUtils.contains(audValueArray, "zzz2.com")); + Assert.assertTrue(ArrayUtils.contains(audValueArray, "zzz3.com")); + Assert.assertTrue(ArrayUtils.contains(audValueArray, "zzzR.com")); + Assert.assertFalse(ArrayUtils.contains(audValueArray, clientId)); + } + + @Test(groups = "wso2.is", description = "Verify the scopes updated by action in the access token ", + dependsOnMethods = "testGetAccessTokenFromRefreshToken") + public void testScopeUpdateOperationsFromPreIssueAccessTokenActionForRefreshTokenGrant() throws Exception { + + String[] scopes = accessTokenClaims.getStringClaim("scope").split("\\s+"); + + Assert.assertTrue(ArrayUtils.contains(scopes, "new_test_custom_scope_1")); + Assert.assertTrue(ArrayUtils.contains(scopes, "new_test_custom_scope_2")); + Assert.assertTrue(ArrayUtils.contains(scopes, "new_test_custom_scope_3")); + Assert.assertTrue(ArrayUtils.contains(scopes, "replaced_scope")); + } + + @Test(groups = "wso2.is", description = "Verify the 'expires_in' claim updated by action in the access token", + dependsOnMethods = "testGetAccessTokenFromRefreshToken") + public void testExpiresInClaimReplaceOperationFromPreIssueAccessTokenActionForRefreshTokenGrant() throws Exception { + + Date exp = accessTokenClaims.getDateClaim("exp"); + Date iat = accessTokenClaims.getDateClaim("iat"); + long expiresIn = (exp.getTime() - iat.getTime()) / 1000; + + Assert.assertEquals(expiresIn, UPDATED_EXPIRY_TIME_BY_ACTION); + } + + private HttpResponse sendTokenRequestForRefreshGrant() throws IOException { + + List parameters = new ArrayList<>(); + parameters.add(new BasicNameValuePair("grant_type", OAuth2Constant.OAUTH2_GRANT_TYPE_REFRESH_TOKEN)); + parameters.add(new BasicNameValuePair(OAuth2Constant.OAUTH2_GRANT_TYPE_REFRESH_TOKEN, refreshToken)); + + List
headers = new ArrayList<>(); + headers.add(new BasicHeader(AUTHORIZATION_HEADER, + OAuth2Constant.BASIC_HEADER + " " + getBase64EncodedString(clientId, clientSecret))); + headers.add(new BasicHeader("Content-Type", "application/x-www-form-urlencoded")); + headers.add(new BasicHeader("User-Agent", OAuth2Constant.USER_AGENT)); + + return sendPostRequest(client, headers, parameters, + getTenantQualifiedURL(ACCESS_TOKEN_ENDPOINT, tenantInfo.getDomain())); + } + + private void sendAuthorizeRequest() throws Exception { + + List urlParameters = new ArrayList<>(); + urlParameters.add(new BasicNameValuePair("response_type", OAuth2Constant.OAUTH2_GRANT_TYPE_CODE)); + urlParameters.add(new BasicNameValuePair("client_id", clientId)); + urlParameters.add(new BasicNameValuePair("redirect_uri", OAuth2Constant.CALLBACK_URL)); + + String scopes = String.join(" ", requestedScopes); + urlParameters.add(new BasicNameValuePair("scope", scopes)); + + HttpResponse response = sendPostRequestWithParameters(client, urlParameters, + getTenantQualifiedURL(AUTHORIZE_ENDPOINT_URL, tenantInfo.getDomain())); + + Header locationHeader = response.getFirstHeader(OAuth2Constant.HTTP_RESPONSE_HEADER_LOCATION); + assertNotNull(locationHeader, "Location header expected for authorize request is not available"); + EntityUtils.consume(response.getEntity()); + + response = sendGetRequest(client, locationHeader.getValue()); + + Map keyPositionMap = new HashMap<>(1); + keyPositionMap.put("name=\"sessionDataKey\"", 1); + List keyValues = + DataExtractUtil.extractDataFromResponse(response, keyPositionMap); + assertNotNull(keyValues, "SessionDataKey key value is null"); + + sessionDataKey = keyValues.get(0).getValue(); + assertNotNull(sessionDataKey, "Session data key is null"); + EntityUtils.consume(response.getEntity()); + } + + public void performUserLogin() throws Exception { + + HttpResponse response = sendLoginPostForCustomUsers(client, sessionDataKey, TEST_USER, TEST_WSO2); + + Header locationHeader = response.getFirstHeader(OAuth2Constant.HTTP_RESPONSE_HEADER_LOCATION); + assertNotNull(locationHeader, "Location header expected post login is not available."); + EntityUtils.consume(response.getEntity()); + + response = sendGetRequest(client, locationHeader.getValue()); + locationHeader = response.getFirstHeader(OAuth2Constant.HTTP_RESPONSE_HEADER_LOCATION); + assertNotNull(locationHeader, "Redirection URL to the application with authorization code is null."); + EntityUtils.consume(response.getEntity()); + + authorizationCode = getAuthorizationCodeFromURL(locationHeader.getValue()); + assertNotNull(authorizationCode); + } + + private HttpResponse sendTokenRequestForCodeGrant() throws Exception { + + List urlParameters = new ArrayList<>(); + urlParameters.add(new BasicNameValuePair("code", authorizationCode)); + urlParameters.add(new BasicNameValuePair("grant_type", OAUTH2_GRANT_TYPE_AUTHORIZATION_CODE)); + urlParameters.add(new BasicNameValuePair("redirect_uri", OAuth2Constant.CALLBACK_URL)); + urlParameters.add(new BasicNameValuePair("client_id", clientId)); + + String scopes = String.join(" ", requestedScopes); + urlParameters.add(new BasicNameValuePair("scope", scopes)); + + List
headers = new ArrayList<>(); + headers.add(new BasicHeader(AUTHORIZATION_HEADER, + OAuth2Constant.BASIC_HEADER + " " + getBase64EncodedString(clientId, clientSecret))); + headers.add(new BasicHeader("Content-Type", "application/x-www-form-urlencoded")); + headers.add(new BasicHeader("User-Agent", OAuth2Constant.USER_AGENT)); + + return sendPostRequest(client, headers, urlParameters, + getTenantQualifiedURL(ACCESS_TOKEN_ENDPOINT, tenantInfo.getDomain())); + } + + private String getAuthorizationCodeFromURL(String location) { + + URI uri = URI.create(location); + return URLEncodedUtils.parse(uri, StandardCharsets.UTF_8).stream() + .filter(param -> "code".equals(param.getName())) + .map(NameValuePair::getValue) + .findFirst() + .orElse(null); + } + + private String createPreIssueAccessTokenAction() throws IOException { + + AuthenticationType authenticationType = new AuthenticationType(); + authenticationType.setType(AuthenticationType.TypeEnum.BASIC); + Map authProperties = new HashMap<>(); + authProperties.put(USERNAME_PROPERTY, MOCK_SERVER_AUTH_BASIC_USERNAME); + authProperties.put(PASSWORD_PROPERTY, MOCK_SERVER_AUTH_BASIC_PASSWORD); + authenticationType.setProperties(authProperties); + + Endpoint endpoint = new Endpoint(); + endpoint.setUri(EXTERNAL_SERVICE_URI); + endpoint.setAuthentication(authenticationType); + + ActionModel actionModel = new ActionModel(); + actionModel.setName("Access Token Pre Issue"); + actionModel.setDescription("This is a test pre issue access token type"); + actionModel.setEndpoint(endpoint); + + return createAction(PRE_ISSUE_ACCESS_TOKEN_API_PATH, actionModel); + } + + private void addUser() throws Exception { + + UserObject userInfo = new UserObject(); + userInfo.setUserName(TEST_USER); + userInfo.setPassword(TEST_WSO2); + userInfo.setName(new Name().givenName("test_user_given_name")); + userInfo.getName().setFamilyName("test_user_last_name"); + userInfo.addEmail(new Email().value("test.user@gmail.com")); + userId = scim2RestClient.createUser(userInfo); + } + + private String createOIDCAppWithClaims() throws Exception { + + List userClaimConfigs = Arrays.asList( + new UserClaimConfig.Builder().localClaimUri("http://wso2.org/claims/givenname"). + oidcClaimUri("given_name").build(), + new UserClaimConfig.Builder().localClaimUri("http://wso2.org/claims/lastname"). + oidcClaimUri("family_name").build() + ); + + ApplicationConfig applicationConfig = new ApplicationConfig.Builder() + .claimsList(userClaimConfigs) + .grantTypes(new ArrayList<>(Arrays.asList("authorization_code", "refresh_token"))) + .tokenType(ApplicationConfig.TokenType.JWT) + .expiryTime(APP_CONFIGURED_EXPIRY_TIME) + .skipConsent(true) + .build(); + + ApplicationResponseModel application = addApplication(applicationConfig); + String applicationId = application.getId(); + + OpenIDConnectConfiguration oidcConfig = getOIDCInboundDetailsOfApplication(applicationId); + clientId = oidcConfig.getClientId(); + clientSecret = oidcConfig.getClientSecret(); + + return applicationId; + } + + private JWTClaimsSet getJWTClaimSetFromToken(String jwtToken) throws ParseException { + + SignedJWT signedJWT = SignedJWT.parse(jwtToken); + return signedJWT.getJWTClaimsSet(); + } +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/dataprovider/model/ActionResponse.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/dataprovider/model/ActionResponse.java new file mode 100644 index 00000000000..3ea145ab3fd --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/dataprovider/model/ActionResponse.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.identity.integration.test.actions.dataprovider.model; + +/** + * This class is used to represent the response from the extension, when an action is invoked. + */ +public class ActionResponse { + + private final int statusCode; + private final String responseBody; + + public ActionResponse(int statusCode, String responseBody) { + + this.statusCode = statusCode; + this.responseBody = responseBody; + } + + public int getStatusCode() { + + return statusCode; + } + + public String getResponseBody() { + + return responseBody; + } +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/dataprovider/model/ExpectedTokenResponse.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/dataprovider/model/ExpectedTokenResponse.java new file mode 100644 index 00000000000..c2ac527af72 --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/dataprovider/model/ExpectedTokenResponse.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.identity.integration.test.actions.dataprovider.model; + +/** + * This class is used to represent the response from the token api, in a pre issue access token action invocation. + */ +public class ExpectedTokenResponse { + + private final int statusCode; + private final String errorMessage; + private final String errorDescription; + + public ExpectedTokenResponse(int statusCode, String errorMessage, String errorDescription) { + + this.statusCode = statusCode; + this.errorMessage = errorMessage; + this.errorDescription = errorDescription; + } + + public int getStatusCode() { + + return statusCode; + } + + public String getErrorMessage() { + + return errorMessage; + } + + public String getErrorDescription() { + + return errorDescription; + } +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/mockserver/ActionsMockServer.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/mockserver/ActionsMockServer.java index d49b0e36c56..102d8bc265b 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/mockserver/ActionsMockServer.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/actions/mockserver/ActionsMockServer.java @@ -39,6 +39,7 @@ public class ActionsMockServer { private WireMockServer wireMockServer; + public void startServer() { wireMockServer = new WireMockServer(WireMockConfiguration.wireMockConfig().port(8587)); @@ -63,6 +64,17 @@ public void setupStub(String url, String authMethod, String responseBody) { .withBody(responseBody))); } + public void setupStub(String url, String authMethod, String responseBody, int statusCode) { + + wireMockServer.stubFor(post(urlEqualTo(url)) + .withHeader("Authorization", matching(authMethod)) + .willReturn(aResponse() + .withStatus(statusCode) + .withHeader("Content-Type", "application/json") + .withHeader("Connection", "Close") + .withBody(responseBody))); + } + public String getReceivedRequestPayload(String url) { List requestList = wireMockServer.findAll(postRequestedFor(urlEqualTo(url))); diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/application/authz/AbstractApplicationAuthzTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/application/authz/AbstractApplicationAuthzTestCase.java deleted file mode 100644 index 5032fd1967b..00000000000 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/application/authz/AbstractApplicationAuthzTestCase.java +++ /dev/null @@ -1,189 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.wso2.identity.integration.test.application.authz; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpResponse; -import org.apache.http.NameValuePair; -import org.apache.http.client.HttpClient; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.entity.UrlEncodedFormEntity; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.config.Lookup; -import org.apache.http.cookie.CookieSpecProvider; -import org.apache.http.message.BasicNameValuePair; -import org.wso2.carbon.identity.application.common.model.xsd.InboundAuthenticationConfig; -import org.wso2.carbon.identity.application.common.model.xsd.InboundAuthenticationRequestConfig; -import org.wso2.carbon.identity.application.common.model.xsd.LocalAndOutboundAuthenticationConfig; -import org.wso2.carbon.identity.application.common.model.xsd.ServiceProvider; -import org.wso2.carbon.identity.entitlement.stub.EntitlementPolicyAdminServiceEntitlementException; -import org.wso2.carbon.identity.entitlement.stub.dto.PolicyDTO; -import org.wso2.carbon.identity.sso.saml.stub.IdentitySAMLSSOConfigServiceIdentityException; -import org.wso2.carbon.identity.sso.saml.stub.types.SAMLSSOServiceProviderDTO; -import org.wso2.identity.integration.common.clients.application.mgt.ApplicationManagementServiceClient; -import org.wso2.identity.integration.common.clients.entitlement.EntitlementPolicyServiceClient; -import org.wso2.identity.integration.common.clients.sso.saml.SAMLSSOConfigServiceClient; -import org.wso2.identity.integration.common.clients.usermgt.remote.RemoteUserStoreManagerServiceClient; -import org.wso2.identity.integration.common.utils.ISIntegrationTest; -import org.wso2.identity.integration.test.utils.CommonConstants; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.rmi.RemoteException; -import java.util.ArrayList; -import java.util.List; - -/** - * Abstract test class for application authorization based on XACML policy. - */ -public class AbstractApplicationAuthzTestCase extends ISIntegrationTest { - - // SAML Application attributes - protected static final String USER_AGENT = "Apache-HttpClient/4.2.5 (java 1.5)"; - protected static final String INBOUND_AUTH_TYPE = "samlsso"; - protected static final String ACS_URL = "http://localhost:" + CommonConstants.DEFAULT_TOMCAT_PORT + "/%s/home.jsp"; - protected static final String COMMON_AUTH_URL = "https://localhost:" + CommonConstants.IS_DEFAULT_HTTPS_PORT + "/commonauth"; - protected static final String SAML_SSO_LOGIN_URL = "http://localhost:" + CommonConstants.DEFAULT_TOMCAT_PORT + "/%s/samlsso?SAML2.HTTPBinding=%s"; - protected static final String NAMEID_FORMAT = "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"; - protected static final String LOGIN_URL = "/carbon/admin/login.jsp"; - private static final Log log = LogFactory.getLog(AbstractApplicationAuthzTestCase.class); - - protected ApplicationManagementServiceClient applicationManagementServiceClient; - protected SAMLSSOConfigServiceClient ssoConfigServiceClient; - protected RemoteUserStoreManagerServiceClient remoteUSMServiceClient; - protected EntitlementPolicyServiceClient entitlementPolicyClient; - - protected HttpClient httpClientAzUser; - protected HttpClient httpClientNonAzUser; - - protected Lookup cookieSpecRegistry; - protected RequestConfig requestConfig; - - protected HttpResponse sendSAMLMessage(String url, String samlMsgKey, String samlMsgValue) throws IOException { - - List urlParameters = new ArrayList<>(); - HttpPost post = new HttpPost(url); - post.setHeader("User-Agent", USER_AGENT); - urlParameters.add(new BasicNameValuePair(samlMsgKey, samlMsgValue)); - post.setEntity(new UrlEncodedFormEntity(urlParameters)); - return httpClientAzUser.execute(post); - } - - protected String extractDataFromResponse(HttpResponse response) throws IOException { - - BufferedReader rd = new BufferedReader( - new InputStreamReader(response.getEntity().getContent())); - StringBuilder result = new StringBuilder(); - String line; - while ((line = rd.readLine()) != null) { - result.append(line); - } - rd.close(); - return result.toString(); - } - - protected void createApplication(String applicationName) throws Exception { - - ServiceProvider serviceProvider = new ServiceProvider(); - serviceProvider.setApplicationName(applicationName); - serviceProvider.setDescription("This is a test Service Provider for AZ test"); - applicationManagementServiceClient.createApplication(serviceProvider); - - serviceProvider = applicationManagementServiceClient.getApplication(applicationName); - - InboundAuthenticationRequestConfig requestConfig = new InboundAuthenticationRequestConfig(); - requestConfig.setInboundAuthType(INBOUND_AUTH_TYPE); - requestConfig.setInboundAuthKey(applicationName); - - - InboundAuthenticationConfig inboundAuthenticationConfig = new InboundAuthenticationConfig(); - inboundAuthenticationConfig.setInboundAuthenticationRequestConfigs( - new InboundAuthenticationRequestConfig[]{requestConfig}); - - serviceProvider.setInboundAuthenticationConfig(inboundAuthenticationConfig); - - LocalAndOutboundAuthenticationConfig outboundAuthConfig = new LocalAndOutboundAuthenticationConfig(); - outboundAuthConfig.setEnableAuthorization(true); - serviceProvider.setLocalAndOutBoundAuthenticationConfig(outboundAuthConfig); - applicationManagementServiceClient.updateApplicationData(serviceProvider); - } - - protected void deleteApplication(String applicationName) throws Exception { - - applicationManagementServiceClient.deleteApplication(applicationName); - ssoConfigServiceClient.removeServiceProvider(applicationName); - } - - protected void createRole(String roleName) throws Exception { - - log.info("Creating role " + roleName); - remoteUSMServiceClient.addRole(roleName, new String[0], null); - } - - protected void deleteRole(String roleName) throws Exception { - - log.info("Deleting role " + roleName); - remoteUSMServiceClient.deleteRole(roleName); - } - - protected void createUser(String username, String password, String[] roles) throws Exception { - - log.info("Creating User " + username); - remoteUSMServiceClient.addUser(username, password, roles, null, null, true); - } - - protected void deleteUser(String username) throws Exception { - - log.info("Deleting User " + username); - remoteUSMServiceClient.deleteUser(username); - } - - protected void createSAMLApp(String applicationName, boolean singleLogout, boolean signResponse, boolean signAssertion) - throws RemoteException, IdentitySAMLSSOConfigServiceIdentityException { - - SAMLSSOServiceProviderDTO samlssoServiceProviderDTO = new SAMLSSOServiceProviderDTO(); - samlssoServiceProviderDTO.setIssuer(applicationName); - samlssoServiceProviderDTO.setAssertionConsumerUrls(new String[]{String.format(ACS_URL, - applicationName)}); - samlssoServiceProviderDTO.setDefaultAssertionConsumerUrl(String.format(ACS_URL, applicationName)); - samlssoServiceProviderDTO.setNameIDFormat(NAMEID_FORMAT); - samlssoServiceProviderDTO.setDoSingleLogout(singleLogout); - samlssoServiceProviderDTO.setLoginPageURL(LOGIN_URL); - samlssoServiceProviderDTO.setDoSignResponse(signResponse); - samlssoServiceProviderDTO.setDoSignAssertions(signAssertion); - ssoConfigServiceClient.addServiceProvider(samlssoServiceProviderDTO); - } - - protected void setupXACMLPolicy(String policyId, String xacmlPolicy) - throws InterruptedException, RemoteException, EntitlementPolicyAdminServiceEntitlementException { - - PolicyDTO policy = new PolicyDTO(); - policy.setPolicy(xacmlPolicy); - policy.setPolicy(policy.getPolicy().replaceAll(">\\s+<", "><").trim()); - policy.setVersion("3.0"); - policy.setPolicyId(policyId); - entitlementPolicyClient.addPolicy(policy); - Thread.sleep(5000); // waiting for the policy to deploy - entitlementPolicyClient - .publishPolicies(new String[]{policyId}, new String[]{"PDP Subscriber"}, "CREATE", true, null, 1); - } -} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/application/authz/ApplicationAuthzTenantTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/application/authz/ApplicationAuthzTenantTestCase.java deleted file mode 100644 index 9021c996edd..00000000000 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/application/authz/ApplicationAuthzTenantTestCase.java +++ /dev/null @@ -1,222 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.wso2.identity.integration.test.application.authz; - -import org.apache.axis2.context.ConfigurationContext; -import org.apache.axis2.context.ConfigurationContextFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpResponse; -import org.apache.http.client.config.CookieSpecs; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.config.RegistryBuilder; -import org.apache.http.cookie.CookieSpecProvider; -import org.apache.http.impl.client.BasicCookieStore; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.cookie.RFC6265CookieSpecProvider; -import org.apache.http.util.EntityUtils; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.carbon.automation.engine.context.TestUserMode; -import org.wso2.carbon.utils.multitenancy.MultitenantUtils; -import org.wso2.identity.integration.common.clients.application.mgt.ApplicationManagementServiceClient; -import org.wso2.identity.integration.common.clients.entitlement.EntitlementPolicyServiceClient; -import org.wso2.identity.integration.common.clients.sso.saml.SAMLSSOConfigServiceClient; -import org.wso2.identity.integration.common.clients.usermgt.remote.RemoteUserStoreManagerServiceClient; -import org.wso2.identity.integration.common.utils.ISIntegrationTest; -import org.wso2.identity.integration.test.util.Utils; -import org.wso2.identity.integration.test.utils.CommonConstants; -import org.wso2.identity.integration.test.utils.UserUtil; - -import java.io.File; -import java.net.URL; - -/** - * Test class to test tenant authorization based on XACML policy. - */ -public class ApplicationAuthzTenantTestCase extends AbstractApplicationAuthzTestCase { - - private static final String AZ_TEST_TENANT_ROLE = "Internal/azTestTenantRole"; - private static final String HTTP_REDIRECT = "HTTP-Redirect"; - private static final String AZ_TEST_TENANT_USER = "azTestTenantUser"; - private static final String AZ_TEST_TENANT_USER_PW = "azTest@123"; - private static final String NON_AZ_TEST_TENANT_USER = "nonAzTestTenantUser"; - private static final String NON_AZ_TEST_TENANT_USER_PW = "nonAzTest@123"; - private static final Log log = LogFactory.getLog(ApplicationAuthzTenantTestCase.class); - private static final String APPLICATION_NAME = "travelocity.com-saml-tenantwithoutsigning"; - private static final String POLICY_ID = "spTenantAuthPolicy"; - private static final String POLICY = - "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " " + - APPLICATION_NAME + "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " " + - AZ_TEST_TENANT_ROLE + "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - ""; - - private String userId; - private String tenantQualifiedCommonAuthURL; - - @BeforeClass(alwaysRun = true) - public void testInit() throws Exception { - - super.init(TestUserMode.TENANT_ADMIN); - tenantQualifiedCommonAuthURL = getTenantQualifiedURL(COMMON_AUTH_URL, tenantInfo.getDomain()); - ConfigurationContext configContext = ConfigurationContextFactory - .createConfigurationContextFromFileSystem(null, null); - applicationManagementServiceClient = - new ApplicationManagementServiceClient(sessionCookie, backendURL, configContext); - ssoConfigServiceClient = - new SAMLSSOConfigServiceClient(backendURL, sessionCookie); - remoteUSMServiceClient = new RemoteUserStoreManagerServiceClient(backendURL, sessionCookie); - entitlementPolicyClient = new EntitlementPolicyServiceClient(backendURL, sessionCookie); - - cookieSpecRegistry = RegistryBuilder.create() - .register(CookieSpecs.DEFAULT, new RFC6265CookieSpecProvider()) - .build(); - requestConfig = RequestConfig.custom() - .setCookieSpec(CookieSpecs.DEFAULT) - .build(); - httpClientAzUser = HttpClientBuilder.create().setDefaultCookieStore(new BasicCookieStore()) - .setDefaultRequestConfig(requestConfig) - .setDefaultCookieSpecRegistry(cookieSpecRegistry) - .build(); - httpClientNonAzUser = HttpClientBuilder.create().setDefaultCookieStore(new BasicCookieStore()) - .setDefaultRequestConfig(requestConfig) - .setDefaultCookieSpecRegistry(cookieSpecRegistry) - .build(); - - createRole(AZ_TEST_TENANT_ROLE); - createUser(AZ_TEST_TENANT_USER, AZ_TEST_TENANT_USER_PW, new String[]{AZ_TEST_TENANT_ROLE}); - userId = UserUtil.getUserId(MultitenantUtils.getTenantAwareUsername(AZ_TEST_TENANT_USER), isServer.getContextTenant()); - - createUser(NON_AZ_TEST_TENANT_USER, NON_AZ_TEST_TENANT_USER_PW, new String[0]); - createApplication(APPLICATION_NAME); - createSAMLApp(APPLICATION_NAME, true, false, false); - setupXACMLPolicy(POLICY_ID, POLICY); - } - - @AfterClass(alwaysRun = true) - public void testClear() throws Exception { - - deleteUser(AZ_TEST_TENANT_USER); - deleteUser(NON_AZ_TEST_TENANT_USER); - deleteRole(AZ_TEST_TENANT_ROLE); - deleteApplication(APPLICATION_NAME); - entitlementPolicyClient.publishPolicies(new String[]{POLICY_ID}, new String[]{"PDP " + - "Subscriber"}, "DELETE", true, null, 1); - entitlementPolicyClient.removePolicy(POLICY_ID); - - ssoConfigServiceClient = null; - applicationManagementServiceClient = null; - remoteUSMServiceClient = null; - httpClientAzUser = null; - } - - @Test(alwaysRun = true, description = "Test authorized tenant user login by evaluating the policy", groups = "wso2.is") - public void testAuthorizedTenantSAMLSSOLogin() throws Exception { - - HttpResponse response; - response = - Utils.sendGetRequest(String.format(SAML_SSO_LOGIN_URL, APPLICATION_NAME, HTTP_REDIRECT), USER_AGENT, - httpClientAzUser); - String sessionKey = Utils.extractDataFromResponse(response, CommonConstants.SESSION_DATA_KEY, 1); - response = Utils.sendPOSTMessage(sessionKey, tenantQualifiedCommonAuthURL, USER_AGENT, ACS_URL, APPLICATION_NAME, - AZ_TEST_TENANT_USER, AZ_TEST_TENANT_USER_PW, httpClientAzUser, tenantQualifiedCommonAuthURL); - - String locationHeader = Utils.getRedirectUrl(response); - if (Utils.requestMissingClaims(response)) { - String pastrCookie = Utils.getPastreCookie(response); - Assert.assertNotNull(pastrCookie, "pastr cookie not found in response."); - EntityUtils.consume(response.getEntity()); - - response = Utils.sendPOSTConsentMessage(response, tenantQualifiedCommonAuthURL, USER_AGENT, locationHeader, - httpClientAzUser, pastrCookie); - } - EntityUtils.consume(response.getEntity()); - - if (Utils.requestMissingClaims(response)) { - String pastrCookie = Utils.getPastreCookie(response); - Assert.assertNotNull(pastrCookie, "pastr cookie not found in response."); - EntityUtils.consume(response.getEntity()); - - response = Utils.sendPOSTConsentMessage(response, tenantQualifiedCommonAuthURL, USER_AGENT, - String.format(ACS_URL, APPLICATION_NAME), - httpClientAzUser, pastrCookie); - EntityUtils.consume(response.getEntity()); - } - - response = Utils.sendRedirectRequest(response, USER_AGENT, ACS_URL, APPLICATION_NAME, - httpClientAzUser); - String samlResponse = Utils.extractDataFromResponse(response, CommonConstants.SAML_RESPONSE_PARAM, 5); - response = sendSAMLMessage(String.format(ACS_URL, APPLICATION_NAME), CommonConstants - .SAML_RESPONSE_PARAM, samlResponse); - String resultPage = extractDataFromResponse(response); - Assert.assertTrue(resultPage.contains("You are logged in as " + userId), - "SAML SSO Login should be successful and page should have a message \"You are logged in as " + userId + "\""); - } - - @Test(alwaysRun = true, description = "Test unauthorized tenant user login by evaluating the policy", groups = "wso2.is") - public void testUnauthorizedTenantSAMLSSOLogin() throws Exception { - - HttpResponse response = Utils.sendGetRequest(String.format(SAML_SSO_LOGIN_URL, APPLICATION_NAME, - HTTP_REDIRECT), USER_AGENT, httpClientNonAzUser); - String sessionKey = Utils.extractDataFromResponse(response, CommonConstants.SESSION_DATA_KEY, 1); - response = Utils.sendPOSTMessage(sessionKey, tenantQualifiedCommonAuthURL, USER_AGENT, ACS_URL, APPLICATION_NAME, - NON_AZ_TEST_TENANT_USER, NON_AZ_TEST_TENANT_USER_PW, httpClientNonAzUser, - tenantQualifiedCommonAuthURL); - - String redirectUrl = Utils.getRedirectUrl(response); - if (Utils.requestMissingClaims(response)) { - String pastrCookie = Utils.getPastreCookie(response); - Assert.assertNotNull(pastrCookie, "pastr cookie not found in response."); - EntityUtils.consume(response.getEntity()); - - response = Utils.sendPOSTConsentMessage(response, tenantQualifiedCommonAuthURL, USER_AGENT, redirectUrl, - httpClientNonAzUser, pastrCookie); - redirectUrl = Utils.getRedirectUrl(response); - } - EntityUtils.consume(response.getEntity()); - response = Utils.sendGetRequest(redirectUrl, USER_AGENT, httpClientNonAzUser); - String responseString = extractDataFromResponse(response); - Assert.assertTrue(responseString.contains("Authorization Failed"), - "SAML SSO Login should be unsuccessful and page should have a message \"Authorization failed for " + NON_AZ_TEST_TENANT_USER + "\""); - } -} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/application/authz/ApplicationAuthzTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/application/authz/ApplicationAuthzTestCase.java deleted file mode 100644 index 4731f53edc1..00000000000 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/application/authz/ApplicationAuthzTestCase.java +++ /dev/null @@ -1,237 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.wso2.identity.integration.test.application.authz; - -import org.apache.axis2.context.ConfigurationContext; -import org.apache.axis2.context.ConfigurationContextFactory; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpResponse; -import org.apache.http.client.config.CookieSpecs; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.config.RegistryBuilder; -import org.apache.http.cookie.CookieSpecProvider; -import org.apache.http.impl.client.BasicCookieStore; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.cookie.RFC6265CookieSpecProvider; -import org.apache.http.util.EntityUtils; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.carbon.automation.engine.context.TestUserMode; -import org.wso2.carbon.identity.entitlement.stub.EntitlementPolicyAdminServiceEntitlementException; -import org.wso2.carbon.identity.entitlement.stub.dto.PolicyDTO; -import org.wso2.carbon.utils.multitenancy.MultitenantUtils; -import org.wso2.identity.integration.common.clients.application.mgt.ApplicationManagementServiceClient; -import org.wso2.identity.integration.common.clients.entitlement.EntitlementPolicyServiceClient; -import org.wso2.identity.integration.common.clients.sso.saml.SAMLSSOConfigServiceClient; -import org.wso2.identity.integration.common.clients.usermgt.remote.RemoteUserStoreManagerServiceClient; -import org.wso2.identity.integration.test.util.Utils; -import org.wso2.identity.integration.test.utils.CommonConstants; -import org.wso2.identity.integration.test.utils.UserUtil; - -import java.rmi.RemoteException; - -public class ApplicationAuthzTestCase extends AbstractApplicationAuthzTestCase { - - private static final String AZ_TEST_ROLE = "Internal/azTestRole"; - private static final String HTTP_REDIRECT = "HTTP-Redirect"; - private static final String AZ_TEST_USER = "azTestUser"; - private static final String AZ_TEST_USER_PW = "azTest@123"; - private static final String NON_AZ_TEST_USER = "nonAzTestUser"; - private static final String NON_AZ_TEST_USER_PW = "nonAzTest@123"; - private static final Log log = LogFactory.getLog(ApplicationAuthzTestCase.class); - private static final String APPLICATION_NAME = "travelocity.com"; - private static final String POLICY_ID = "spAuthPolicy"; - private static final String POLICY = - "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " " + - APPLICATION_NAME + "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " " + - AZ_TEST_ROLE + "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - ""; - - private String userId; - - @BeforeClass(alwaysRun = true) - public void testInit() throws Exception { - - super.init(TestUserMode.SUPER_TENANT_ADMIN); - - ConfigurationContext configContext = ConfigurationContextFactory - .createConfigurationContextFromFileSystem(null, null); - applicationManagementServiceClient = - new ApplicationManagementServiceClient(sessionCookie, backendURL, configContext); - ssoConfigServiceClient = - new SAMLSSOConfigServiceClient(backendURL, sessionCookie); - remoteUSMServiceClient = new RemoteUserStoreManagerServiceClient(backendURL, sessionCookie); - entitlementPolicyClient = new EntitlementPolicyServiceClient(backendURL, sessionCookie); - - cookieSpecRegistry = RegistryBuilder.create() - .register(CookieSpecs.DEFAULT, new RFC6265CookieSpecProvider()) - .build(); - requestConfig = RequestConfig.custom() - .setCookieSpec(CookieSpecs.DEFAULT) - .build(); - httpClientAzUser = HttpClientBuilder.create().setDefaultCookieStore(new BasicCookieStore()) - .setDefaultRequestConfig(requestConfig) - .setDefaultCookieSpecRegistry(cookieSpecRegistry) - .build(); - httpClientNonAzUser = HttpClientBuilder.create().setDefaultCookieStore(new BasicCookieStore()) - .setDefaultRequestConfig(requestConfig) - .setDefaultCookieSpecRegistry(cookieSpecRegistry) - .build(); - - createRole(AZ_TEST_ROLE); - createUser(AZ_TEST_USER, AZ_TEST_USER_PW, new String[]{AZ_TEST_ROLE}); - userId = UserUtil.getUserId(MultitenantUtils.getTenantAwareUsername(AZ_TEST_USER), isServer.getContextTenant()); - - createUser(NON_AZ_TEST_USER, NON_AZ_TEST_USER_PW, new String[0]); - createApplication(APPLICATION_NAME); - createSAMLApp(APPLICATION_NAME, true, true, true); - setupXACMLPolicy(POLICY_ID, POLICY); - } - - protected void setupXACMLPolicy(String policyId, String xacmlPolicy) - throws InterruptedException, RemoteException, EntitlementPolicyAdminServiceEntitlementException { - - PolicyDTO policy = new PolicyDTO(); - policy.setPolicy(xacmlPolicy); - policy.setPolicy(policy.getPolicy().replaceAll(">\\s+<", "><").trim()); - policy.setVersion("3.0"); - policy.setPolicyId(policyId); - entitlementPolicyClient.addPolicy(policy); - Thread.sleep(5000); // waiting for the policy to deploy - entitlementPolicyClient - .publishPolicies(new String[]{policyId}, new String[]{"PDP Subscriber"}, "CREATE", true, null, 1); - - } - - @AfterClass(alwaysRun = true) - public void testClear() throws Exception { - - deleteUser(AZ_TEST_USER); - deleteUser(NON_AZ_TEST_USER); - deleteRole(AZ_TEST_ROLE); - deleteApplication(APPLICATION_NAME); - entitlementPolicyClient.publishPolicies(new String[]{POLICY_ID}, new String[]{"PDP " + - "Subscriber"}, "DELETE", true, null, 1); - entitlementPolicyClient.removePolicy(POLICY_ID); - - ssoConfigServiceClient = null; - applicationManagementServiceClient = null; - remoteUSMServiceClient = null; - httpClientAzUser = null; - } - - - @Test(alwaysRun = true, description = "Testing authorized user login", groups = "wso2.is") - public void testAuthorizedSAMLSSOLogin() throws Exception { - - HttpResponse response; - response = - Utils.sendGetRequest(String.format(SAML_SSO_LOGIN_URL, APPLICATION_NAME, HTTP_REDIRECT), USER_AGENT, - httpClientAzUser); - - String sessionKey = Utils.extractDataFromResponse(response, CommonConstants.SESSION_DATA_KEY, 1); - response = Utils.sendPOSTMessage(sessionKey, COMMON_AUTH_URL, USER_AGENT, ACS_URL, APPLICATION_NAME, - AZ_TEST_USER, AZ_TEST_USER_PW, httpClientAzUser); - - String locationHeader = Utils.getRedirectUrl(response); - if (Utils.requestMissingClaims(response)) { - String pastrCookie = Utils.getPastreCookie(response); - Assert.assertNotNull(pastrCookie, "pastr cookie not found in response."); - EntityUtils.consume(response.getEntity()); - - response = Utils.sendPOSTConsentMessage(response, COMMON_AUTH_URL, USER_AGENT, locationHeader, - httpClientAzUser, pastrCookie); - } - EntityUtils.consume(response.getEntity()); - - if (Utils.requestMissingClaims(response)) { - String pastrCookie = Utils.getPastreCookie(response); - Assert.assertNotNull(pastrCookie, "pastr cookie not found in response."); - EntityUtils.consume(response.getEntity()); - - response = Utils.sendPOSTConsentMessage(response, COMMON_AUTH_URL, USER_AGENT, - String.format(ACS_URL, APPLICATION_NAME), - httpClientAzUser, pastrCookie); - EntityUtils.consume(response.getEntity()); - } - - response = Utils.sendRedirectRequest(response, USER_AGENT, ACS_URL, APPLICATION_NAME, httpClientAzUser); - String samlResponse = Utils.extractDataFromResponse(response, CommonConstants.SAML_RESPONSE_PARAM, 5); - - response = sendSAMLMessage(String.format(ACS_URL, APPLICATION_NAME), CommonConstants - .SAML_RESPONSE_PARAM, samlResponse); - String resultPage = extractDataFromResponse(response); - - Assert.assertTrue(resultPage.contains("You are logged in as " + userId), - "SAML SSO Login should be successful and page should have a message \"You are logged in as\" " + userId); - - } - - @Test(alwaysRun = true, description = "Testing unauthorized user login", groups = "wso2.is") - public void testUnauthorizedSAMLSSOLogin() throws Exception { - - HttpResponse response = Utils.sendGetRequest(String.format(SAML_SSO_LOGIN_URL, APPLICATION_NAME, - HTTP_REDIRECT), USER_AGENT, httpClientNonAzUser); - String sessionKey = Utils.extractDataFromResponse(response, CommonConstants.SESSION_DATA_KEY, 1); - response = Utils.sendPOSTMessage(sessionKey, COMMON_AUTH_URL, USER_AGENT, ACS_URL, APPLICATION_NAME, - NON_AZ_TEST_USER, NON_AZ_TEST_USER_PW, httpClientNonAzUser); - - String locationHeader = Utils.getRedirectUrl(response); - if (Utils.requestMissingClaims(response)) { - String pastrCookie = Utils.getPastreCookie(response); - Assert.assertNotNull(pastrCookie, "pastr cookie not found in response."); - EntityUtils.consume(response.getEntity()); - - response = Utils.sendPOSTConsentMessage(response, COMMON_AUTH_URL, USER_AGENT, locationHeader, - httpClientNonAzUser, pastrCookie); - } - String redirectUrl = Utils.getRedirectUrl(response); - EntityUtils.consume(response.getEntity()); - response = Utils.sendGetRequest(redirectUrl, USER_AGENT, httpClientNonAzUser); - String responseString = extractDataFromResponse(response); - Assert.assertTrue(responseString.contains("Authorization Failed"), - "SAML SSO Login should be unsuccessful and page should have a message \"Authorization failed for\" " + NON_AZ_TEST_USER); - - } -} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/auth/PasswordlessSMSOTPAuthTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/auth/PasswordlessSMSOTPAuthTestCase.java new file mode 100644 index 00000000000..85de57987ae --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/auth/PasswordlessSMSOTPAuthTestCase.java @@ -0,0 +1,293 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.identity.integration.test.auth; + +import org.apache.http.Header; +import org.apache.http.HttpResponse; +import org.apache.http.NameValuePair; +import org.apache.http.client.HttpClient; +import org.apache.http.client.config.CookieSpecs; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.config.Lookup; +import org.apache.http.config.RegistryBuilder; +import org.apache.http.cookie.CookieSpecProvider; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.client.LaxRedirectStrategy; +import org.apache.http.impl.cookie.RFC6265CookieSpecProvider; +import org.apache.http.message.BasicHeader; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; +import org.wso2.carbon.automation.engine.context.TestUserMode; +import org.wso2.identity.integration.test.base.MockApplicationServer; +import org.wso2.identity.integration.test.base.MockSMSProvider; +import org.wso2.identity.integration.test.oidc.OIDCAbstractIntegrationTest; +import org.wso2.identity.integration.test.oidc.OIDCUtilTest; +import org.wso2.identity.integration.test.oidc.bean.OIDCApplication; +import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.ApplicationModel; +import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.AuthenticationSequence; +import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.AuthenticationStep; +import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.Authenticator; +import org.wso2.identity.integration.test.rest.api.server.notification.sender.v1.model.Properties; +import org.wso2.identity.integration.test.rest.api.server.notification.sender.v1.model.SMSSender; +import org.wso2.identity.integration.test.rest.api.user.common.model.Name; +import org.wso2.identity.integration.test.rest.api.user.common.model.PhoneNumbers; +import org.wso2.identity.integration.test.rest.api.user.common.model.UserObject; +import org.wso2.identity.integration.test.restclients.NotificationSenderRestClient; +import org.wso2.identity.integration.test.utils.DataExtractUtil; +import org.wso2.identity.integration.test.utils.OAuth2Constant; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.wso2.identity.integration.test.utils.OAuth2Constant.ACCESS_TOKEN_ENDPOINT; +import static org.wso2.identity.integration.test.utils.OAuth2Constant.AUTHORIZATION_HEADER; +import static org.wso2.identity.integration.test.utils.OAuth2Constant.AUTHORIZE_ENDPOINT_URL; +import static org.wso2.identity.integration.test.utils.OAuth2Constant.OAUTH2_GRANT_TYPE_AUTHORIZATION_CODE; + +/** + * This class includes the test cases for passwordless SMS OTP authentication. + */ +public class PasswordlessSMSOTPAuthTestCase extends OIDCAbstractIntegrationTest { + + public static final String USERNAME = "passwordlessuser"; + public static final String PASSWORD = "Oidcsessiontestuser@123"; + public static final String MOBILE = "+941111111111"; + public static final String SMS_SENDER_REQUEST_FORMAT = "{\"content\": {{body}}, \"to\": {{mobile}} }"; + + private HttpClient client; + + NotificationSenderRestClient notificationSenderRestClient; + + private OIDCApplication oidcApplication; + private UserObject userObject; + private String sessionDataKey; + private String authorizationCode; + + private MockSMSProvider mockSMSProvider; + private MockApplicationServer mockApplicationServer; + + private TestUserMode userMode; + + @Factory(dataProvider = "testExecutionContextProvider") + public PasswordlessSMSOTPAuthTestCase(TestUserMode userMode) { + + this.userMode = userMode; + } + + @DataProvider(name = "testExecutionContextProvider") + public static Object[][] getTestExecutionContext() throws Exception { + + return new Object[][]{ + {TestUserMode.SUPER_TENANT_USER}, + {TestUserMode.TENANT_USER}, + }; + } + + @BeforeClass(alwaysRun = true) + public void testInit() throws Exception { + + super.init(userMode); + mockSMSProvider = new MockSMSProvider(); + mockSMSProvider.start(); + + mockApplicationServer = new MockApplicationServer(); + mockApplicationServer.start(); + + super.init(); + + Lookup cookieSpecRegistry = RegistryBuilder.create() + .register(CookieSpecs.DEFAULT, new RFC6265CookieSpecProvider()) + .build(); + RequestConfig requestConfig = RequestConfig.custom() + .setCookieSpec(CookieSpecs.DEFAULT) + .build(); + client = HttpClientBuilder.create() + .setDefaultRequestConfig(requestConfig) + .setDefaultCookieSpecRegistry(cookieSpecRegistry) + .setRedirectStrategy(new LaxRedirectStrategy()) + .build(); + + backendURL = backendURL.replace("services/", ""); + + oidcApplication = initOIDCApplication(); + ApplicationModel applicationModel = initApplication(); + createApplication(applicationModel, oidcApplication); + + userObject = initUser(); + createUser(userObject); + + notificationSenderRestClient = new NotificationSenderRestClient(backendURL, tenantInfo); + SMSSender smsSender = initSMSSender(); + notificationSenderRestClient.createSMSProvider(smsSender); + } + + private static SMSSender initSMSSender() { + + SMSSender smsSender = new SMSSender(); + smsSender.setProvider(MockSMSProvider.SMS_SENDER_PROVIDER_TYPE); + smsSender.setProviderURL(MockSMSProvider.SMS_SENDER_URL); + smsSender.contentType(SMSSender.ContentTypeEnum.JSON); + ArrayList properties = new ArrayList<>(); + properties.add(new Properties().key("body").value(SMS_SENDER_REQUEST_FORMAT)); + smsSender.setProperties(properties); + return smsSender; + } + + @AfterClass(alwaysRun = true) + public void atEnd() throws Exception { + + deleteApplication(oidcApplication); + deleteUser(userObject); + notificationSenderRestClient.deleteSMSProvider(); + notificationSenderRestClient.closeHttpClient(); + restClient.closeHttpClient(); + scim2RestClient.closeHttpClient(); + + mockSMSProvider.stop(); + mockApplicationServer.stop(); + } + + @Test(groups = "wso2.is", description = "Test passwordless authentication with SMS OTP") + public void testPasswordlessAuthentication() throws Exception { + + sendAuthorizeRequest(); + performUserLogin(); + HttpResponse response = sendTokenRequestForCodeGrant(); + + assertNotNull(response); + assertEquals(response.getStatusLine().getStatusCode(), 200); + } + + private void sendAuthorizeRequest() throws Exception { + + List urlParameters = new ArrayList<>(); + urlParameters.add(new BasicNameValuePair("response_type", OAuth2Constant.OAUTH2_GRANT_TYPE_CODE)); + urlParameters.add(new BasicNameValuePair("client_id", oidcApplication.getClientId())); + urlParameters.add(new BasicNameValuePair("redirect_uri", oidcApplication.getCallBackURL())); + + urlParameters.add(new BasicNameValuePair("scope", "openid")); + + HttpResponse response = sendPostRequestWithParameters(client, urlParameters, + getTenantQualifiedURL(AUTHORIZE_ENDPOINT_URL, tenantInfo.getDomain())); + + Map keyPositionMap = new HashMap<>(1); + keyPositionMap.put("name=\"sessionDataKey\"", 1); + List keyValues = DataExtractUtil.extractDataFromResponse(response, keyPositionMap); + assertNotNull(keyValues, "Session data key"); + + sessionDataKey = keyValues.get(0).getValue(); + assertNotNull(sessionDataKey, "Session data key"); + EntityUtils.consume(response.getEntity()); + } + + private void performUserLogin() throws Exception { + + sendLoginPostForIdentifier(client, sessionDataKey, userObject.getUserName()); + HttpResponse response = sendLoginPostForOtp(client, sessionDataKey, mockSMSProvider.getOTP()); + EntityUtils.consume(response.getEntity()); + + authorizationCode = mockApplicationServer.getAuthorizationCodeForApp(oidcApplication.getApplicationName()); + assertNotNull(authorizationCode); + } + + private void sendLoginPostForIdentifier(HttpClient client, String sessionDataKey, String username) + throws IOException { + + List urlParameters = new ArrayList<>(); + urlParameters.add(new BasicNameValuePair("username", username)); + urlParameters.add(new BasicNameValuePair("sessionDataKey", sessionDataKey)); + sendPostRequestWithParameters(client, urlParameters, + getTenantQualifiedURL(OAuth2Constant.COMMON_AUTH_URL, tenantInfo.getDomain())); + } + + private HttpResponse sendLoginPostForOtp(HttpClient client, String sessionDataKey, String otp) + throws IOException { + + List urlParameters = new ArrayList<>(); + urlParameters.add(new BasicNameValuePair("OTPcode", otp)); + urlParameters.add(new BasicNameValuePair("sessionDataKey", sessionDataKey)); + return sendPostRequestWithParameters(client, urlParameters, + getTenantQualifiedURL(OAuth2Constant.COMMON_AUTH_URL, tenantInfo.getDomain())); + } + + private HttpResponse sendTokenRequestForCodeGrant() throws Exception { + + List urlParameters = new ArrayList<>(); + urlParameters.add(new BasicNameValuePair("code", authorizationCode)); + urlParameters.add(new BasicNameValuePair("grant_type", OAUTH2_GRANT_TYPE_AUTHORIZATION_CODE)); + urlParameters.add(new BasicNameValuePair("redirect_uri", oidcApplication.getCallBackURL())); + urlParameters.add(new BasicNameValuePair("client_id", oidcApplication.getClientSecret())); + + urlParameters.add(new BasicNameValuePair("scope", "openid")); + + List
headers = new ArrayList<>(); + headers.add(new BasicHeader(AUTHORIZATION_HEADER, + OAuth2Constant.BASIC_HEADER + " " + getBase64EncodedString(oidcApplication.getClientId(), + oidcApplication.getClientSecret()))); + headers.add(new BasicHeader("Content-Type", "application/x-www-form-urlencoded")); + headers.add(new BasicHeader("User-Agent", OAuth2Constant.USER_AGENT)); + + return sendPostRequest(client, headers, urlParameters, + getTenantQualifiedURL(ACCESS_TOKEN_ENDPOINT, tenantInfo.getDomain())); + } + + private OIDCApplication initOIDCApplication() { + + OIDCApplication playgroundApp = new OIDCApplication(MockApplicationServer.Constants.APP1.NAME, + MockApplicationServer.Constants.APP1.CALLBACK_URL); + return playgroundApp; + } + + private ApplicationModel initApplication() { + + ApplicationModel application = new ApplicationModel(); + AuthenticationSequence authenticationSequence = new AuthenticationSequence(); + AuthenticationStep stepsItem = new AuthenticationStep(); + stepsItem.setId(1); + Authenticator optionsItem = new Authenticator(); + optionsItem.setAuthenticator("sms-otp-authenticator"); + optionsItem.setIdp("LOCAL"); + stepsItem.addOptionsItem(optionsItem); + authenticationSequence.addStepsItem(stepsItem); + authenticationSequence.setType(AuthenticationSequence.TypeEnum.USER_DEFINED); + authenticationSequence.setSubjectStepId(1); + application.setAuthenticationSequence(authenticationSequence); + return application; + } + + protected UserObject initUser() { + + UserObject user = new UserObject(); + user.setUserName(USERNAME); + user.setPassword(PASSWORD); + user.setName(new Name().givenName(OIDCUtilTest.firstName).familyName(OIDCUtilTest.lastName)); + user.addPhoneNumbers(new PhoneNumbers().value(MOBILE).type("mobile")); + return user; + } +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/auth/SecondaryStoreUserLoginTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/auth/SecondaryStoreUserLoginTestCase.java index 598c449f16a..e23be6dec76 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/auth/SecondaryStoreUserLoginTestCase.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/auth/SecondaryStoreUserLoginTestCase.java @@ -208,7 +208,7 @@ private void checkAuthorizationCode(String sessionDataKeyConsent) throws Excepti private void createAndRegisterPlaygroundApplication() throws Exception { - playgroundApp = new OIDCApplication(PLAYGROUND_APP_NAME, PLAYGROUND_APP_CONTEXT, PLAYGROUND_APP_CALLBACK_URI); + playgroundApp = new OIDCApplication(PLAYGROUND_APP_NAME, PLAYGROUND_APP_CALLBACK_URI); playgroundApp.addRequiredClaim(OIDCUtilTest.emailClaimUri); playgroundApp.addRequiredClaim(OIDCUtilTest.firstNameClaimUri); playgroundApp.addRequiredClaim(OIDCUtilTest.lastNameClaimUri); diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/base/MockApplicationServer.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/base/MockApplicationServer.java new file mode 100644 index 00000000000..ab5455d8fd8 --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/base/MockApplicationServer.java @@ -0,0 +1,231 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.identity.integration.test.base; + +import com.github.tomakehurst.wiremock.WireMockServer; +import com.github.tomakehurst.wiremock.core.WireMockConfiguration; +import com.github.tomakehurst.wiremock.extension.ResponseTransformerV2; +import com.github.tomakehurst.wiremock.extension.responsetemplating.ResponseTemplateTransformer; +import com.github.tomakehurst.wiremock.http.Response; +import com.github.tomakehurst.wiremock.stubbing.ServeEvent; +import org.wso2.identity.integration.common.utils.ISIntegrationTest; +import org.wso2.identity.integration.test.util.Utils; + +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; +import static com.github.tomakehurst.wiremock.client.WireMock.matching; +import static com.github.tomakehurst.wiremock.client.WireMock.post; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; + +/** + * Mock application server to test OIDC related flows. + */ +public class MockApplicationServer { + + public static class MockClient { + private final AtomicReference authorizationCode = new AtomicReference<>(); + private final AtomicReference errorCode = new AtomicReference<>(); + + public AtomicReference getAuthorizationCode() { + return authorizationCode; + } + + public AtomicReference getErrorCode() { + return errorCode; + } + } + + public static class Constants { + public static class APP1 { + public static final String CALLBACK_URL = "https://localhost:8091/dummyApp/oauth2client"; + public static final String NAME = "playground.appone"; + public static final String CALLBACK_URL_PATH = "/dummyApp/oauth2client"; + } + + public static class APP2 { + public static final String CALLBACK_URL = "https://localhost:8091/dummyApp2/oauth2client"; + public static final String NAME = "playground.apptwo"; + public static final String CALLBACK_URL_PATH = "/dummyApp2/oauth2client"; + } + } + + private final Map apps = new HashMap<>(); + + private WireMockServer wireMockServer; + + public MockApplicationServer() { + + MockClient app1 = new MockClient(); + MockClient app2 = new MockClient(); + apps.put(Constants.APP1.NAME, app1); + apps.put(Constants.APP2.NAME, app2); + } + + public void start() { + + wireMockServer = new WireMockServer(WireMockConfiguration.wireMockConfig() + .httpsPort(8091) + .httpDisabled(true) + .keystorePath(Paths.get(Utils.getResidentCarbonHome(), "repository", "resources", "security", + ISIntegrationTest.KEYSTORE_NAME).toAbsolutePath().toString()) + .keystorePassword("wso2carbon") + .keyManagerPassword("wso2carbon") + .extensions(new ResponseTemplateTransformer(null, true, null, null), + new ResponseTransformerV2() { + + @Override + public Response transform(Response response, ServeEvent serveEvent) { + + AtomicReference authorizationCode + = (AtomicReference) serveEvent.getTransformerParameters().get("code"); + authorizationCode.set(serveEvent.getRequest().getQueryParams().get("code") + .firstValue()); + return response; + } + + @Override + public boolean applyGlobally() { + return false; + } + + @Override + public String getName() { + return "authz-code-transformer"; + } + }, + new ResponseTransformerV2() { + + @Override + public Response transform(Response response, ServeEvent serveEvent) { + + AtomicReference errorCode + = (AtomicReference) serveEvent.getTransformerParameters().get("error"); + errorCode.set(serveEvent.getRequest().getQueryParams().get("error").firstValue()); + return response; + } + + @Override + public boolean applyGlobally() { + return false; + } + + @Override + public String getName() { + return "error-code-transformer"; + } + })); + + wireMockServer.start(); + + // Configure the mock client endpoints for App 1 + configureMockEndpointsForApp(Constants.APP1.CALLBACK_URL_PATH, apps.get(Constants.APP1.NAME)); + // Configure the mock client endpoints for App 2 + configureMockEndpointsForApp(Constants.APP2.CALLBACK_URL_PATH, apps.get(Constants.APP2.NAME)); + } + + public void stop() { + + if (wireMockServer != null) { + wireMockServer.stop(); + } + } + + private void configureMockEndpointsForApp(String urlPath, MockClient app) { + + try { + wireMockServer.stubFor(get(urlPathEqualTo(urlPath)) + .withQueryParam("code", matching(".*")) + .willReturn(aResponse() + .withTransformers("response-template", "authz-code-transformer") + .withTransformerParameter("code", app.getAuthorizationCode()) + .withTransformerParameter("error", app.getErrorCode()) + .withStatus(200))); + wireMockServer.stubFor(post(urlPathEqualTo(urlPath)) + .withQueryParam("code", matching(".*")) + .willReturn(aResponse() + .withTransformers("response-template", "authz-code-transformer") + .withTransformerParameter("code", app.getAuthorizationCode()) + .withTransformerParameter("error", app.getErrorCode()) + .withStatus(200))); + wireMockServer.stubFor(get(urlPathEqualTo(urlPath)) + .withQueryParam("code", matching(".*")) + .withQueryParam("session_state", matching(".*")) + .willReturn(aResponse() + .withTransformers("response-template", "authz-code-transformer") + .withTransformerParameter("code", app.getAuthorizationCode()) + .withTransformerParameter("error", app.getErrorCode()) + .withStatus(200))); + wireMockServer.stubFor(post(urlPathEqualTo(urlPath)) + .withQueryParam("code", matching(".*")) + .withQueryParam("session_state", matching(".*")) + .willReturn(aResponse() + .withTransformers("response-template", "authz-code-transformer") + .withTransformerParameter("code", app.getAuthorizationCode()) + .withTransformerParameter("error", app.getErrorCode()) + .withStatus(200))); + wireMockServer.stubFor(get(urlPathEqualTo(urlPath)) + .withQueryParam("error_description", matching(".*")) + .withQueryParam("error", matching(".*")) + .willReturn(aResponse() + .withTransformers("response-template", "error-code-transformer") + .withTransformerParameter("code", app.getAuthorizationCode()) + .withTransformerParameter("error", app.getErrorCode()) + .withStatus(200))); + wireMockServer.stubFor(get(urlEqualTo(urlPath)) + .willReturn(aResponse() + .withTransformers("response-template") + .withStatus(200))); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public void verifyLogoutRedirectionForApp(String appName) { + + wireMockServer.verify(getRequestedFor(urlEqualTo(getCallbackUrlPath(appName)))); + } + + public String getAuthorizationCodeForApp(String appName) { + + return apps.get(appName).getAuthorizationCode().get(); + } + + public String getErrorCode(String appName) { + + return apps.get(appName).getErrorCode().get(); + } + + private String getCallbackUrlPath(String appName) { + switch (appName) { + case Constants.APP1.NAME: + return Constants.APP1.CALLBACK_URL_PATH; + case Constants.APP2.NAME: + return Constants.APP2.CALLBACK_URL_PATH; + default: + throw new IllegalArgumentException("Unknown app name: " + appName); + } + } +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/base/MockOIDCIdentityProvider.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/base/MockOIDCIdentityProvider.java index 59533900bd1..b3e985570f8 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/base/MockOIDCIdentityProvider.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/base/MockOIDCIdentityProvider.java @@ -30,6 +30,8 @@ import com.nimbusds.jose.crypto.RSASSASigner; import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.SignedJWT; +import org.wso2.carbon.utils.security.KeystoreUtils; +import org.wso2.identity.integration.common.utils.ISIntegrationTest; import org.wso2.identity.integration.test.util.Utils; import java.io.FileInputStream; @@ -69,8 +71,9 @@ public void start() { wireMockServer = new WireMockServer(WireMockConfiguration.wireMockConfig() .httpsPort(8089) + .httpDisabled(true) .keystorePath(Paths.get(Utils.getResidentCarbonHome(), "repository", "resources", "security", - "wso2carbon.p12").toAbsolutePath().toString()) + ISIntegrationTest.KEYSTORE_NAME).toAbsolutePath().toString()) .keystorePassword("wso2carbon") .keyManagerPassword("wso2carbon") .extensions( @@ -178,7 +181,7 @@ public void verifyForLogoutFlow() { private String buildIdToken() throws Exception { - KeyStore wso2KeyStore = getKeyStoreFromFile("wso2carbon.p12", "wso2carbon", + KeyStore wso2KeyStore = getKeyStoreFromFile(ISIntegrationTest.KEYSTORE_NAME, "wso2carbon", Utils.getResidentCarbonHome()); RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) wso2KeyStore.getKey("wso2carbon", "wso2carbon".toCharArray()); @@ -212,7 +215,7 @@ private KeyStore getKeyStoreFromFile(String keystoreName, String password, Strin Path tenantKeystorePath = Paths.get(home, "repository", "resources", "security", keystoreName); FileInputStream file = new FileInputStream(tenantKeystorePath.toString()); - KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); + KeyStore keystore = KeystoreUtils.getKeystoreInstance(ISIntegrationTest.KEYSTORE_TYPE); keystore.load(file, password.toCharArray()); return keystore; } diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/base/MockSMSProvider.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/base/MockSMSProvider.java new file mode 100644 index 00000000000..646c131c0b1 --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/base/MockSMSProvider.java @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.identity.integration.test.base; + +import com.github.tomakehurst.wiremock.WireMockServer; +import com.github.tomakehurst.wiremock.core.WireMockConfiguration; +import com.github.tomakehurst.wiremock.extension.ResponseTransformerV2; +import com.github.tomakehurst.wiremock.extension.responsetemplating.ResponseTemplateTransformer; +import com.github.tomakehurst.wiremock.http.Response; +import com.github.tomakehurst.wiremock.stubbing.ServeEvent; +import com.jayway.jsonpath.JsonPath; +import org.wso2.identity.integration.common.utils.ISIntegrationTest; +import org.wso2.identity.integration.test.util.Utils; + +import java.nio.file.Paths; +import java.util.concurrent.atomic.AtomicReference; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.matchingJsonPath; +import static com.github.tomakehurst.wiremock.client.WireMock.post; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; + +/** + * Mock SMS Provider for testing SMS related flows. + */ +public class MockSMSProvider { + + public static final String SMS_SENDER_URL = "https://localhost:8090/sms/send"; + public static final String SMS_SENDER_PROVIDER_TYPE = "Custom"; + + private WireMockServer wireMockServer; + private final AtomicReference otp = new AtomicReference<>(); + + public void start() { + + wireMockServer = new WireMockServer(WireMockConfiguration.wireMockConfig() + .httpsPort(8090) + .httpDisabled(true) + .keystorePath(Paths.get(Utils.getResidentCarbonHome(), "repository", "resources", "security", + ISIntegrationTest.KEYSTORE_NAME).toAbsolutePath().toString()) + .keystorePassword("wso2carbon") + .keyManagerPassword("wso2carbon") + .extensions( + new ResponseTemplateTransformer(null, true, null, null), + new ResponseTransformerV2() { + @Override + public Response transform(Response response, ServeEvent serveEvent) { + + // Extract the content value from the request body. + String content = + JsonPath.parse(serveEvent.getRequest().getBodyAsString()).read("$.content"); + + String regex = "\\b\\d{6}\\b"; + + Pattern pattern = Pattern.compile(regex); + Matcher matcher = pattern.matcher(content); + + if (matcher.find()) { + String extractedOtp = matcher.group(); + // Store the content value for later use. + otp.set(extractedOtp); + } + return response; + } + + @Override + public boolean applyGlobally() { + return false; + } + + @Override + public String getName() { + return "otp-transformer"; + } + })); + + wireMockServer.start(); + + // Configure the mock SMS endpoints. + configureMockEndpoints(); + } + + public void stop() { + + if (wireMockServer != null) { + wireMockServer.stop(); + } + } + + private void configureMockEndpoints() { + + try { + wireMockServer.stubFor(post(urlEqualTo("/sms/send")) + .withRequestBody(matchingJsonPath("$.content")) + .withRequestBody(matchingJsonPath("$.to")) + .willReturn(aResponse() + .withTransformers("response-template", "otp-transformer") + .withStatus(200))); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public String getOTP() { + + return otp.get(); + } +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/base/TomcatInitializerTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/base/TomcatInitializerTestCase.java index a51b660a1f3..2fdc751b53c 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/base/TomcatInitializerTestCase.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/base/TomcatInitializerTestCase.java @@ -43,16 +43,7 @@ public class TomcatInitializerTestCase extends ISIntegrationTest { "travelocity.com-registrymount", "avis.com", "PassiveSTSSampleApp", - "playground.appone", - "playground.apptwo", - "playground2", - // TODO: Check and remove the following with openid tests - "travelocity.com-openid-smartconsumerwithclaims", - "travelocity.com-openid-smartconsumerwithoutclaims", - "travelocity.com-openid-dumbconsumerwithclaims", - "travelocity.com-openid-dumbconsumerwithoutclaims" - // TODO: End of openid apps - + "playground2" }; private static final Log LOG = LogFactory.getLog(TomcatInitializerTestCase.class); diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/entitlement/EntitlementAdminServiceTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/entitlement/EntitlementAdminServiceTestCase.java deleted file mode 100644 index ce3ea0f88f0..00000000000 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/entitlement/EntitlementAdminServiceTestCase.java +++ /dev/null @@ -1,100 +0,0 @@ -/* -* Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. -* -* WSO2 Inc. licenses this file to you under the Apache License, -* Version 2.0 (the "License"); you may not use this file except -* in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, -* software distributed under the License is distributed on an -* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -* KIND, either express or implied. See the License for the -* specific language governing permissions and limitations -* under the License. -*/ - -package org.wso2.identity.integration.test.entitlement; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.testng.Assert; -import org.wso2.identity.integration.common.clients.entitlement.EntitlementAdminServiceClient; -import org.wso2.identity.integration.common.utils.ISIntegrationTest; - -public class EntitlementAdminServiceTestCase extends ISIntegrationTest{ - - private EntitlementAdminServiceClient entitlementAdminClient; - private static final Log log = LogFactory.getLog(EntitlementAdminServiceTestCase.class); - private static final String REQUEST_1 = " admin http://localhost:8280/services/echo read "; - - @BeforeClass(alwaysRun = true) - public void testInit() throws Exception { - super.init(); - entitlementAdminClient = new EntitlementAdminServiceClient(backendURL, sessionCookie); - } - - @AfterClass(alwaysRun = true) - public void atEnd() throws Exception { - - } - - @Test(groups = "wso2.is", description = "Check get policy algorithm") - public void testGetGlobalPolicyAlgorithm() throws Exception { - Assert.assertNotNull(entitlementAdminClient.getGlobalPolicyAlgorithm(), "Getting the policy algorithm has failed with null return."); - } - - @Test(groups = "wso2.is", description = "Check get pdp data", dependsOnMethods="testGetGlobalPolicyAlgorithm") - public void testGetPDPData() throws Exception { - entitlementAdminClient.getPDPData(); - } - - @Test(groups = "wso2.is", description = "Check policy request", dependsOnMethods="testGetPDPData") - public void testDoTestRequest() throws Exception { - Assert.assertNotNull(entitlementAdminClient.doTestRequest(REQUEST_1), "Testing the policy request has failed with null return."); - } - - @Test(groups = "wso2.is", description = "Check get PIP attribute finder data", dependsOnMethods="testDoTestRequest") - public void testGetPIPAttributeFinderData() throws Exception { - entitlementAdminClient.getPIPAttributeFinderData("urn:oasis:names:tc:xacml:1.0:subject:subject-id"); -// TODO - fix request -// Assert.assertNotNull(entitlementAdminClient.getPIPAttributeFinderData("urn:oasis:names:tc:xacml:1.0:subject:subject-id"), "Getting PIP attribute finder data has failed with null return."); - } - - @Test(groups = "wso2.is", description = "Check get PIP resource finder data", dependsOnMethods="testGetPIPAttributeFinderData") - public void testGetPIPResourceFinderData() throws Exception { - Assert.assertNotNull(entitlementAdminClient.getPIPResourceFinderData("urn:oasis:names:tc:xacml:1.0:resource:resource-id"), "Getting PIP resouce finder data has failed with null return."); - } - - @Test(groups = "wso2.is", description = "Check get policy finder data", dependsOnMethods="testGetPIPResourceFinderData") - public void testGetPolicyFinderData() throws Exception { - entitlementAdminClient.getPolicyFinderData(""); -// TODO - fix request -// Assert.assertNotNull(entitlementAdminClient.getPolicyFinderData(""), "Getting policy finder data has failed with null return."); - } - - @Test(groups = "wso2.is", description = "Check refresh attribute finder", dependsOnMethods="testGetPolicyFinderData") - public void testRefreshAttributeFinder() throws Exception { - entitlementAdminClient.refreshAttributeFinder("*"); - } - - @Test(groups = "wso2.is", description = "Check refresh policy finder", dependsOnMethods="testRefreshAttributeFinder") - public void testRefreshPolicyFinders() throws Exception { - entitlementAdminClient.refreshPolicyFinders("*"); - } - - @Test(groups = "wso2.is", description = "Check refresh resouce finder", dependsOnMethods="testRefreshPolicyFinders") - public void testRefreshResourceFinder() throws Exception { - entitlementAdminClient.refreshResourceFinder("*"); - } - - @Test(groups = "wso2.is", description = "Check set global policy algorithm", dependsOnMethods="testRefreshResourceFinder") - public void testSetGlobalPolicyAlgorithm() throws Exception { - entitlementAdminClient.setGlobalPolicyAlgorithm("Algo"); - } -} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/entitlement/EntitlementJSONSupportMultiDecisionProfileTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/entitlement/EntitlementJSONSupportMultiDecisionProfileTestCase.java deleted file mode 100644 index 6bb97bc2735..00000000000 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/entitlement/EntitlementJSONSupportMultiDecisionProfileTestCase.java +++ /dev/null @@ -1,314 +0,0 @@ -/* - * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.identity.integration.test.entitlement; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.cxf.jaxrs.client.WebClient; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.carbon.identity.entitlement.stub.dto.PolicyDTO; -import org.wso2.identity.integration.common.clients.entitlement.EntitlementPolicyServiceClient; -import org.wso2.identity.integration.common.clients.usermgt.remote.RemoteUserStoreManagerServiceClient; -import org.wso2.identity.integration.common.utils.ISIntegrationTest; - -import java.io.File; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; -import java.util.Scanner; -import java.util.Set; - -/** - * This is to test the full flow of XACML Multi Decision Profile scenario - */ -public class EntitlementJSONSupportMultiDecisionProfileTestCase extends ISIntegrationTest { - - private static final Log log = LogFactory.getLog(EntitlementJSONSupportMultiDecisionProfileTestCase.class); - private EntitlementPolicyServiceClient entitlementPolicyClient; - private RemoteUserStoreManagerServiceClient remoteUserStoreManagerServiceClient; - private final static String ENDPOINT_ADDRESS = "https://localhost:9853/api/identity/entitlement/decision"; - private final static String PASSWORD = "Wso2@test123"; - private final static String ROLE = "admin"; - - - private static final String POLICY_ID = "urn:oasis:names:tc:xacml:3.0:web-filter-policy"; - private static final String POLICY = "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " index.jsp\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " publicUser\n" + - " " + - "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " view-welcome\n" + - " view-summary\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " internalUser\n" + - " " + - "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " view-status\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " adminUser\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " modify-welcome\n" + - " modify-summary\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " You can access the" + - " resource index.jsp\n" + - " \n" + - " \n" + - " \n" + - " "; - - @BeforeClass(alwaysRun = true) - public void testInit() throws Exception { - super.init(); - entitlementPolicyClient = new EntitlementPolicyServiceClient(backendURL, sessionCookie); - remoteUserStoreManagerServiceClient = new RemoteUserStoreManagerServiceClient(backendURL, sessionCookie); - PolicyDTO policy = new PolicyDTO(); - policy.setPolicy(POLICY); - entitlementPolicyClient.addPolicy(policy); - entitlementPolicyClient.publishPolicies(new String[]{POLICY_ID}, new String[]{"PDP Subscriber"}, "CREATE", - true, null, 1); - remoteUserStoreManagerServiceClient.addUser("adminUser",PASSWORD, new String[]{ROLE}, null, - "adminUser",false); - remoteUserStoreManagerServiceClient.addUser("publicUser",PASSWORD, new String[]{ROLE}, null, - "publicUser",false); - remoteUserStoreManagerServiceClient.addUser("localUser",PASSWORD, new String[]{ROLE}, null, - "localUser",false); - } - - @Test(groups = "wso2-is", description = "A simple JSON request sample") - public void testPdpJSONSimpleRequest() throws JSONException { - - WebClient client = WebClient.create(ENDPOINT_ADDRESS); - - client.header("Authorization", "Basic YWRtaW46YWRtaW4="); - client.type("application/json"); - client.accept("application/json"); - - client.path("pdp"); - - String request = readReource("entitlement/json/simpleRequest.json"); - String response = readReource("entitlement/json/simpleResponse.json"); - JSONObject objExpected = new JSONObject(response); - - String webRespose = client.post(request, String.class); - JSONObject objReturn = new JSONObject(webRespose); - Assert.assertTrue(areJSONObjectsEqual(objExpected, objReturn), "The response is wrong it should be :"+ response + " But" + - " the response is :" + webRespose); - } - - @Test(groups = "wso2-is", description = "A complex multi-decision JSON request sample") - public void testPdpJSONMultiDecisionRequest() throws JSONException { - - WebClient client = WebClient.create(ENDPOINT_ADDRESS); - - client.header("Authorization", "Basic YWRtaW46YWRtaW4="); - client.type("application/json"); - client.accept("application/json"); - - client.path("pdp"); - - String request = readReource("entitlement/json/complexMDPRequest.json"); - String response = readReource("entitlement/json/complexMDPResponse.json"); - JSONObject objExpected = new JSONObject(response); - - String webRespose = client.post(request, String.class); - JSONObject objReturn = new JSONObject(webRespose); - Assert.assertTrue(areJSONObjectsEqual(objExpected, objReturn), "The response is wrong it should be :"+ response + " But" + - " the response is :" + webRespose); - - } - - @Test(groups = "wso2-is", description = "A complex multi-decision JSON request sample in simple form") - public void testPdpJSONMultiDecisionRequestSimpleForm() throws JSONException { - - WebClient client = WebClient.create(ENDPOINT_ADDRESS); - - client.header("Authorization", "Basic YWRtaW46YWRtaW4="); - client.type("application/json"); - client.accept("application/json"); - - client.path("pdp"); - - String request = readReource("entitlement/json/simpleMDPRequest.json"); - String response = readReource("entitlement/json/simpleMDPResponse.json"); - JSONObject objExpected = new JSONObject(response); - - String webRespose = client.post(request, String.class); - JSONObject objReturn = new JSONObject(webRespose); - Assert.assertTrue(areJSONObjectsEqual(objExpected, objReturn), "The response is wrong it should be :"+ response + " But" + - " the response is :" + webRespose); - } - - @AfterClass(alwaysRun = true) - public void destroy() throws Exception { - - // Remove added policy - entitlementPolicyClient = new EntitlementPolicyServiceClient(backendURL, sessionCookie); - remoteUserStoreManagerServiceClient = new RemoteUserStoreManagerServiceClient(backendURL, sessionCookie); - entitlementPolicyClient.enableDisablePolicy(POLICY_ID, false); - entitlementPolicyClient.removePolicy(POLICY_ID); - remoteUserStoreManagerServiceClient.deleteUser("adminUser"); - remoteUserStoreManagerServiceClient.deleteUser("publicUser"); - remoteUserStoreManagerServiceClient.deleteUser("localUser"); - } - - public static boolean areJSONObjectsEqual(Object ob1, Object ob2) throws JSONException { - - Object obj1Converted = convertJsonElement(ob1); - Object obj2Converted = convertJsonElement(ob2); - return obj1Converted.equals(obj2Converted); - } - - private static Object convertJsonElement(Object elem) throws JSONException { - - if (elem instanceof JSONObject) { - JSONObject obj = (JSONObject) elem; - Iterator keys = obj.keys(); - Map jsonMap = new HashMap<>(); - while (keys.hasNext()) { - String key = keys.next(); - jsonMap.put(key, convertJsonElement(obj.get(key))); - } - return jsonMap; - } else if (elem instanceof JSONArray) { - JSONArray arr = (JSONArray) elem; - Set jsonSet = new HashSet<>(); - for (int i = 0; i < arr.length(); i++) { - jsonSet.add(convertJsonElement(arr.get(i))); - } - return jsonSet; - } else { - return elem; - } - } - - private String readReource(String path) { - - StringBuilder result = new StringBuilder(); - Scanner scanner = null; - try { - //Get file from resources folder - ClassLoader classLoader = getClass().getClassLoader(); - URI filepath = new URI(classLoader.getResource(path).toString()); - - File file = new File(filepath); - - scanner = new Scanner(file); - - while (scanner.hasNextLine()) { - String line = scanner.nextLine(); - result.append(line).append("\n"); - } - - } catch (IOException e) { - log.error("Error occured when reading the file.", e); - } catch (URISyntaxException e) { - log.error("URI syntax error.", e); - } finally { - scanner.close(); - } - return result.toString().replaceAll("\\n\\r|\\n|\\r|\\t|\\s{2,}", "").replaceAll(": ", ":"); - } - -} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/entitlement/EntitlementNotificationTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/entitlement/EntitlementNotificationTestCase.java deleted file mode 100644 index a0e6b7aaf62..00000000000 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/entitlement/EntitlementNotificationTestCase.java +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.identity.integration.test.entitlement; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.carbon.identity.entitlement.stub.dto.PolicyDTO; -import org.wso2.carbon.integration.common.utils.mgt.ServerConfigurationManager; -import org.wso2.carbon.user.mgt.stub.types.carbon.FlaggedName; -import org.wso2.identity.integration.common.clients.UserManagementClient; -import org.wso2.identity.integration.common.clients.entitlement.EntitlementPolicyServiceClient; -import org.wso2.identity.integration.common.utils.ISIntegrationTest; -import org.wso2.identity.integration.test.util.Utils; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -public class EntitlementNotificationTestCase extends ISIntegrationTest { - - private EntitlementPolicyServiceClient entitlementPolicyClient; - private static final Log log = LogFactory.getLog(EntitlementPolicyAdminServiceTestCase.class); - - private static final String POLICY_1_ID = "urn:sample:xacml:2.0:custompolicy"; - private static final String POLICY_1 = " " - + " Custom policy " - + " " - + " admin can read or write echo service " - + " " - + " " - + "admin " - + " " - + " " - + "http://localhost:8280/services/echo " - + " " - + " " - + "read " - + " " - + " " - + "write " - + " " - + " "; - private ServerConfigurationManager serverConfigurationManager; - private File entitlementProperties; - private File notificationMgtProperties; - private UserManagementClient userMgtServiceClient; - - @BeforeClass(alwaysRun = true) - public void testInit() throws Exception { - super.init(); - changeISConfiguration(); - super.init(); - entitlementPolicyClient = new EntitlementPolicyServiceClient(backendURL, sessionCookie); - userMgtServiceClient = new UserManagementClient(backendURL, sessionCookie); - } - - @AfterClass(alwaysRun = true) - public void atEnd() throws Exception { - resetISConfiguration(); - super.init(); - userMgtServiceClient = new UserManagementClient(backendURL, sessionCookie); - userMgtServiceClient.deleteUser("CREATE"); - userMgtServiceClient.deleteUser("UPDATE"); - userMgtServiceClient.deleteUser("DELETE"); - } - - @Test(groups = "wso2.is", description = "Check rest endpoint call on adding a policy") - public void testAddPolicy() throws Exception { - PolicyDTO policy = new PolicyDTO(); - policy.setPolicy(POLICY_1); - entitlementPolicyClient.addPolicy(policy); - // It takes some time to send http post and create user from scim - Thread.sleep(5000); - Assert.assertTrue(isUserExists("CREATE")); - } - - @Test(groups = "wso2.is", description = "Check rest endpoint call on adding a policy", - dependsOnMethods = "updatePolicy") - public void deletePolicy() throws Exception { - entitlementPolicyClient.removePolicy("urn:sample:xacml:2.0:custompolicy"); - // It takes some time to send http post and create user from scim - Thread.sleep(5000); - Assert.assertTrue(isUserExists("DELETE")); - } - - @Test(groups = "wso2.is", description = "Check rest endpoint call on adding a policy", - dependsOnMethods = "testAddPolicy") - public void updatePolicy() throws Exception { - PolicyDTO policy = new PolicyDTO(); - policy.setPolicy(POLICY_1); - entitlementPolicyClient.updatePolicy(policy); - // It takes some time to send http post and create user from scim - Thread.sleep(5000); - Assert.assertTrue(isUserExists("UPDATE")); - } - - private void changeISConfiguration() throws Exception { - changeEntitlementPropertyConfig(); - changeNotificationMgtPropertyConfig(); - serverConfigurationManager.restartGracefully(); - } - - private void changeEntitlementPropertyConfig() throws Exception { - - log.info("Changing entitlement.properties to add EntitlementNotificationExtension"); - - String carbonHome = Utils.getResidentCarbonHome(); - entitlementProperties = new File(carbonHome + File.separator - + "repository" + File.separator + "conf" + File.separator + "identity" + File.separator + - "entitlement.properties"); - File configuredEntitlementProperties = new File(getISResourceLocation() - + File.separator + "entitlement" + File.separator + "config" + File.separator - + "entitlementNotificationEnabled.properties"); - - serverConfigurationManager = new ServerConfigurationManager(isServer); - serverConfigurationManager.applyConfigurationWithoutRestart(configuredEntitlementProperties, - entitlementProperties, true); - } - - private void changeNotificationMgtPropertyConfig() throws Exception { - - log.info("Changing msg-mgt.properties to add EntitlementNotificationExtension"); - - String carbonHome = Utils.getResidentCarbonHome(); - String templateLocation = getISResourceLocation() - + File.separator + "notification-mgt" + File.separator + "templates" + File.separator - + "entitlement"; - String msgMgtPropertiesFileLocation = getISResourceLocation() - + File.separator + "notification-mgt" + File.separator + "config" + File.separator - + "entitlementNotificationMgt.properties"; - - HashMap newProperties = new HashMap<>(); - newProperties.put("json.subscription.policyUpdate.jsonContentTemplate", templateLocation); - replaceProperties(newProperties, msgMgtPropertiesFileLocation); - notificationMgtProperties = new File(carbonHome + File.separator - + "repository" + File.separator + "conf" + File.separator + "identity" + File.separator + - "msg-mgt.properties"); - - File configuredNotificationProperties = new File(msgMgtPropertiesFileLocation); - serverConfigurationManager.applyConfigurationWithoutRestart(configuredNotificationProperties, - notificationMgtProperties, true); - } - - private boolean isUserExists(String userName) throws Exception { - FlaggedName[] nameList = userMgtServiceClient.listAllUsers(userName, 100); - for (FlaggedName name : nameList) { - if (name.getItemName().contains(userName)) { - return true; - } - } - return false; - } - - public void replaceProperties(Map properties, String filePath) throws IOException { - - Properties prop = new Properties(); - FileInputStream input = null; - FileOutputStream outputStream = null; - input = new FileInputStream(filePath); - - prop.load(input); - - for (Map.Entry entry : properties.entrySet()) { - prop.put(entry.getKey(), entry.getValue()); - } - - outputStream = new FileOutputStream(filePath); - prop.store(outputStream, null); - } - - private void resetISConfiguration() throws Exception { - - serverConfigurationManager.restoreToLastConfiguration(false); - } -} \ No newline at end of file diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/entitlement/EntitlementPIPAttributeCacheTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/entitlement/EntitlementPIPAttributeCacheTestCase.java deleted file mode 100644 index 10150b97288..00000000000 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/entitlement/EntitlementPIPAttributeCacheTestCase.java +++ /dev/null @@ -1,225 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.identity.integration.test.entitlement; - -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.carbon.identity.entitlement.stub.EntitlementPolicyAdminServiceEntitlementException; -import org.wso2.carbon.identity.entitlement.stub.EntitlementServiceException; -import org.wso2.carbon.identity.entitlement.stub.dto.PolicyDTO; -import org.wso2.carbon.integration.common.utils.mgt.ServerConfigurationManager; -import org.wso2.identity.integration.common.clients.entitlement.EntitlementPolicyServiceClient; -import org.wso2.identity.integration.common.clients.entitlement.EntitlementServiceClient; -import org.wso2.identity.integration.common.utils.ISIntegrationTest; -import org.wso2.identity.integration.test.util.Utils; - -import java.io.File; -import java.io.FileFilter; -import java.rmi.RemoteException; - -/** - * This class contains test case to test the use case described in https://wso2.org/jira/browse/IDENTITY-4740 - */ -public class EntitlementPIPAttributeCacheTestCase extends ISIntegrationTest { - private EntitlementServiceClient entitlementServiceClient; - private EntitlementPolicyServiceClient entitlementPolicyClient; - private ServerConfigurationManager scm; - - private static final String POLICY_ID = "urn:oasis:names:tc:xacml:3.0:IDENTITY4740"; - private static final String POLICY = "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " fooIDENTITY4740\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " readIDENTITY4740\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " admin@wso2" + - ".com\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " " + - ""; - - @BeforeClass(alwaysRun = true) - public void testInit() throws Exception { - super.init(); - scm = new ServerConfigurationManager(isServer); - entitlementPolicyClient = new EntitlementPolicyServiceClient(backendURL, sessionCookie); - addPolicy(); - addCustomAttributeFinder(); - //call super init since server restart happens in previous step - super.init(); - entitlementServiceClient = new EntitlementServiceClient(backendURL, sessionCookie); - } - - @Test(groups = "wso2.is", description = "Check get decision") - public void testGetPermitDecision() throws EntitlementServiceException, RemoteException, - EntitlementPolicyAdminServiceEntitlementException { - String decision = entitlementServiceClient.getDecision(buildRequest("admin@wso2.com")); - Assert.assertTrue(decision.contains("Permit"), "Entitlement service get decision failed."); - } - - @Test(groups = "wso2.is", dependsOnMethods = {"testGetPermitDecision"}, description = "Check get decision") - public void testGetNotPermitDecision() throws EntitlementServiceException, RemoteException, - EntitlementPolicyAdminServiceEntitlementException { - String decision = entitlementServiceClient.getDecision(buildRequest("non.existing.email@wso2.com")); - Assert.assertTrue(!decision.contains("Permit"), "Entitlement service get decision failed."); - } - - @AfterClass(alwaysRun = true) - public void destroy() throws Exception { - //Remove added policy - entitlementPolicyClient = new EntitlementPolicyServiceClient(backendURL, sessionCookie); - entitlementPolicyClient.enableDisablePolicy(POLICY_ID, false); - entitlementPolicyClient.removePolicy(POLICY_ID); - //Copy default config file - File srcConfigFile = new File(getISResourceLocation() - + File.separator + "entitlement" + File.separator - + "config" + File.separator - + "entitlement_default.properties"); - File targetConfigFile = new File(Utils.getResidentCarbonHome() + File.separator + "repository" - + File.separator + "conf" + File.separator + "identity" + File.separator + - "entitlement.properties"); - - scm.applyConfigurationWithoutRestart(srcConfigFile, targetConfigFile, true); - //remove custom attribute finder from lib - scm.removeFromComponentLib("org.wso2.carbon.identity.custom.pip-4.2.2.jar"); - scm.restartGracefully(); - } - - private void addPolicy() throws Exception { - PolicyDTO policy = new PolicyDTO(); - policy.setPolicy(POLICY); - policy.setPolicy(policy.getPolicy().replaceAll(">\\s+<", "><").trim()); - policy.setVersion("3.0"); - policy.setPolicyId(POLICY_ID); - entitlementPolicyClient.addPolicy(policy); - entitlementPolicyClient.publishPolicies(new String[]{POLICY_ID}, new String[]{"PDP Subscriber"}, "CREATE", - true, null, 1); - } - - private void addCustomAttributeFinder() throws Exception { - File jarFile = getCustomAttributeFinder(); - scm.copyToComponentLib(jarFile); - - //Copy entitlement.properties - File srcConfigFile = new File(getISResourceLocation() - + File.separator + "entitlement" + File.separator - + "config" + File.separator + - "entitlement_custom_attribute_finder.properties"); - File targetConfigFile = new File(Utils.getResidentCarbonHome() + File.separator + "repository" - + File.separator + "conf" + File.separator + "identity" + File.separator + - "entitlement.properties"); - - scm.applyConfigurationWithoutRestart(srcConfigFile, targetConfigFile, true); - scm.restartGracefully(); - } - - private File getCustomAttributeFinder() throws Exception { - - File targetDir = new File( - getISResourceLocation() + File.separator + ".." + File.separator + ".." + File.separator + ".." + - File.separator + ".." + File.separator + ".." + File.separator + ".." + - File.separator + ".." + File.separator + "tests-common" + File.separator + "extensions" + - File.separator + "target"); - if (!targetDir.isDirectory()) { - throw new Exception(targetDir + " is not a directory."); - } - - File[] files = targetDir.listFiles(new FileFilter() { - @Override - public boolean accept(File file) { - String fileName = file.getName(); - if (fileName.indexOf("org.wso2.carbon.identity.custom.pip") >= 0 && !(fileName.indexOf("test") >= 0)) { - return true; - } else { - return false; - } - } - }); - - if (files != null && files.length == 1) { - return files[0]; - } else { - throw new Exception("Could not found custom attribute finder jar"); - } - } - private String buildRequest(String subject) { - String request = "\n" + - "\n" + - "\n" + - "readIDENTITY4740\n" + - "\n" + - "\n" + - "\n" + - "\n" + - "" + subject + - "\n" + - "\n" + - "\n" + - "\n" + - "\n" + - "fooIDENTITY4740\n" + - "\n" + - "\n" + - "" + - ""; - return request; - } -} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/entitlement/EntitlementPolicyAdminServiceTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/entitlement/EntitlementPolicyAdminServiceTestCase.java deleted file mode 100644 index 6ced39a047c..00000000000 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/entitlement/EntitlementPolicyAdminServiceTestCase.java +++ /dev/null @@ -1,295 +0,0 @@ -/* - * Copyright (c) WSO2 LLC. (https://www.wso2.com) All Rights Reserved. - * - * WSO2 LLC. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.identity.integration.test.entitlement; - -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.carbon.identity.entitlement.stub.dto.PaginatedPolicySetDTO; -import org.wso2.carbon.identity.entitlement.stub.dto.PolicyDTO; -import org.wso2.carbon.identity.entitlement.stub.dto.PublisherDataHolder; -import org.wso2.carbon.identity.entitlement.stub.dto.PublisherPropertyDTO; -import org.wso2.identity.integration.common.clients.entitlement.EntitlementPolicyServiceClient; -import org.wso2.identity.integration.common.utils.ISIntegrationTest; - -import java.util.Arrays; -import java.util.stream.Stream; - -public class EntitlementPolicyAdminServiceTestCase extends ISIntegrationTest { - - private EntitlementPolicyServiceClient entitlementPolicyClient; - - private static final String POLICY_1_ID = "urn:sample:xacml:2.0:custompolicy"; - private static final String POLICY_2_ID = "urn:sample:xacml:2.0:custompolicy2"; - private static final String POLICY_1_VERSION = "1"; - private static final String POLICY_1 = " " - + " Custom policy " - + " " - + " admin can read or write echo service " - + " " - + " " - + "admin " - + " " - + " " - + - "http://localhost:8280/services/echo " - + " " - + " " - + "read " - + " " - + " " - + "write " - + " " - + " "; - - private static final String POLICY_2 = " " - + " Custom policy " - + " " - + " admin can read or write echo service " - + " " - + " " - + "admin " - + " " - + " " - + - "http://localhost:8280/services/echo " - + " " - + " " - + "read " - + " " - + " " - + "write " - + " " - + " "; - - @BeforeClass(alwaysRun = true) - public void testInit() throws Exception { - - super.init(); - entitlementPolicyClient = new EntitlementPolicyServiceClient(backendURL, sessionCookie); - } - - @AfterClass(alwaysRun = true) - public void atEnd() throws Exception { - - if (Arrays.asList(entitlementPolicyClient.getAllPolicyIds("*")).contains(POLICY_1_ID)) { - entitlementPolicyClient.removePolicy(POLICY_1_ID, false); - } - } - - @Test(groups = "wso2.is", description = "Check adding a policy") - public void testAddPolicy() throws Exception { - - PolicyDTO policy = new PolicyDTO(); - policy.setPolicy(POLICY_1); - entitlementPolicyClient.addPolicy(policy); - } - - @Test(groups = "wso2.is", description = "Check get specific policy", dependsOnMethods = "testAddPolicy") - public void testGetPolicy() throws Exception { - - PolicyDTO policyDTO = entitlementPolicyClient.getPolicy(POLICY_1_ID, false); - Assert.assertEquals(policyDTO.getPolicyId(), POLICY_1_ID, "Getting the policy with specified Id has failed."); - } - - @Test(groups = "wso2.is", description = "Check get all policy ids", dependsOnMethods = "testGetPolicy") - public void testGetAllPolicyIds() throws Exception { - - Assert.assertTrue(Arrays.asList(entitlementPolicyClient.getAllPolicyIds("*")).contains(POLICY_1_ID), - "Getting all policies has failed."); - } - - @Test(groups = "wso2.is", description = "Check get policy versions", dependsOnMethods = "testGetAllPolicyIds") - public void testGetPolicyVersions() throws Exception { - - Assert.assertTrue( - Arrays.asList(entitlementPolicyClient.getPolicyVersions(POLICY_1_ID)).contains(POLICY_1_VERSION), - "Getting policy versions has failed."); - } - - @Test(groups = "wso2.is", description = "Check get policy by version", dependsOnMethods = "testGetPolicyVersions") - public void testGetPolicyByVersion() throws Exception { - - PolicyDTO policyDTO = entitlementPolicyClient.getPolicyByVersion(POLICY_1_ID, POLICY_1_VERSION); - Assert.assertEquals(policyDTO.getPolicyId(), POLICY_1_ID, "Getting policy by version has failed."); - } - - @Test(groups = "wso2.is", description = "Check get policy with params", dependsOnMethods = "testGetPolicyByVersion") - public void testGetAllPoliciesWithParam() throws Exception { - - PaginatedPolicySetDTO policyDTOPaginated1 = entitlementPolicyClient.getAllPolicies("ALL", "*", 0, false); - PaginatedPolicySetDTO policyDTOPaginated2 = entitlementPolicyClient.getAllPolicies("ALL", "*", 1, false); - PolicyDTO[] policyDTOs1 = policyDTOPaginated1.getPolicySet(); - PolicyDTO[] policyDTOs2 = policyDTOPaginated2.getPolicySet(); - PolicyDTO[] allPolicyDTOs = - Stream.concat(Arrays.stream(policyDTOs1), Arrays.stream(policyDTOs2)).toArray(PolicyDTO[]::new); - boolean exists = false; - - for (PolicyDTO policy : allPolicyDTOs) { - if (POLICY_1_ID.equals(policy.getPolicyId())) { - exists = true; - break; - } - } - Assert.assertTrue(exists, "Getting the policy with params has failed."); - } - - @Test(groups = "wso2.is", description = "Check Getting status data", dependsOnMethods = "testGetAllPoliciesWithParam") - public void testGetStatusData() throws Exception { - - Assert.assertNotNull(entitlementPolicyClient.getStatusData("*", "*", "urn", "*", 1)); - } - - @Test(groups = "wso2.is", description = "Check publishing policies", dependsOnMethods = "testGetStatusData") - public void testPublish() throws Exception { - - entitlementPolicyClient.publishPolicies(new String[]{POLICY_1_ID}, new String[]{"PDP Subscriber"}, "CREATE", - true, null, 1); - Assert.assertNotNull(entitlementPolicyClient.getPolicy(POLICY_1_ID, true)); - } - - @Test(groups = "wso2.is", description = "Check ordering policy", dependsOnMethods = "testPublish") - public void testOrderPolicy() throws Exception { - - entitlementPolicyClient.orderPolicy(POLICY_1_ID, 1); - PolicyDTO publishedPolicy = entitlementPolicyClient.getPolicy(POLICY_1_ID, true); - Assert.assertEquals(publishedPolicy.getPolicyOrder(), 1, "Ordering policy has failed."); - } - - @Test(groups = "wso2.is", description = "Check disabling policy", dependsOnMethods = "testOrderPolicy") - public void testEnableDisablePolicy() throws Exception { - - entitlementPolicyClient.enableDisablePolicy(POLICY_1_ID, false); - PolicyDTO publishedPolicy = entitlementPolicyClient.getPolicy(POLICY_1_ID, true); - Assert.assertFalse(publishedPolicy.getActive(), "Disabling policy has failed."); - entitlementPolicyClient.enableDisablePolicy(POLICY_1_ID, true); - } - - @Test(groups = "wso2.is", description = "Check demoting policy", dependsOnMethods = "testEnableDisablePolicy") - public void testDemotePolicy() throws Exception { - - entitlementPolicyClient.dePromotePolicy(POLICY_1_ID); - Assert.assertNull((entitlementPolicyClient.getPolicy(POLICY_1_ID, true)).getPolicy()); - } - - @Test(groups = "wso2.is", description = "Check remove policy by id", dependsOnMethods = "testDemotePolicy") - public void testRemovePolicy() throws Exception { - - entitlementPolicyClient.removePolicy(POLICY_1_ID, false); - Assert.assertNotNull(entitlementPolicyClient.getAllPolicyIds("*"), "Getting all policy ids has failed."); - Assert.assertFalse(Arrays.asList(entitlementPolicyClient.getAllPolicyIds("*")).contains(POLICY_1_ID), - "Remove policy after adding has failed."); - } - - @Test(groups = "wso2.is", description = "Check adding policies", dependsOnMethods = "testRemovePolicy") - public void testAddPolicies() throws Exception { - - PolicyDTO policy = new PolicyDTO(); - policy.setPolicy(POLICY_2); - PolicyDTO[] policies = new PolicyDTO[1]; - policies[0] = policy; - entitlementPolicyClient.addPolicies(policies); - - PolicyDTO returnPolicies = entitlementPolicyClient.getPolicy(POLICY_2_ID, false); - Assert.assertNotNull(returnPolicies, "Addling policy list has failed with null return."); - Assert.assertEquals(returnPolicies.getPolicyId(), POLICY_2_ID, "Adding policy list has failed."); - } - - @Test(groups = "wso2.is", description = "Check remove policies", dependsOnMethods = "testAddPolicies") - public void testRemovePolicies() throws Exception { - - entitlementPolicyClient.removePolicies(new String[]{POLICY_2_ID}, false); - Assert.assertNotNull(entitlementPolicyClient.getAllPolicyIds("*"), "Getting all policy ids has failed."); - Assert.assertFalse(Arrays.asList(entitlementPolicyClient.getAllPolicyIds("*")).contains(POLICY_2_ID), - "Remove policy after adding has failed."); - } - - @Test(groups = "wso2.is", description = "Check getting subscriber", dependsOnMethods = "testRemovePolicies") - public void testAddSubscriber() throws Exception { - - PublisherDataHolder holder = new PublisherDataHolder(); - holder.setModuleName("test"); - - PublisherPropertyDTO propertyDto = new PublisherPropertyDTO(); - propertyDto.setId("subscriberId"); - propertyDto.setValue("1001"); - propertyDto.setDisplayName("Custom Subscriber"); - PublisherPropertyDTO[] propertyDTOs = new PublisherPropertyDTO[1]; - propertyDTOs[0] = propertyDto; - holder.setPropertyDTOs(propertyDTOs); - entitlementPolicyClient.addSubscriber(holder); - } - - @Test(groups = "wso2.is", description = "Check getting subscriber", dependsOnMethods = "testAddSubscriber") - public void testGetSubscriber() throws Exception { - - PublisherDataHolder subscriber = entitlementPolicyClient.getSubscriber("1001"); - Assert.assertEquals(subscriber.getModuleName(), "test", "Getting subscriber has failed."); - } - - @Test(groups = "wso2.is", description = "Check getting subscriber Ids", dependsOnMethods = "testGetSubscriber") - public void testGetSubscriberIds() throws Exception { - - Assert.assertNotNull(entitlementPolicyClient.getSubscriberIds("*")); - } - - @Test(groups = "wso2.is", description = "Check updating subscriber", dependsOnMethods = "testGetSubscriberIds") - public void testUpdateSubscriber() throws Exception { - - PublisherDataHolder holder = new PublisherDataHolder(); - holder.setModuleName("test2"); - PublisherPropertyDTO propertyDto = new PublisherPropertyDTO(); - propertyDto.setId("subscriberId"); - propertyDto.setValue("1001"); - propertyDto.setDisplayName("Updated Custom Subscriber"); - PublisherPropertyDTO[] propertyDTOs = new PublisherPropertyDTO[1]; - propertyDTOs[0] = propertyDto; - holder.setPropertyDTOs(propertyDTOs); - - entitlementPolicyClient.updateSubscriber(holder); - PublisherDataHolder subscriber = entitlementPolicyClient.getSubscriber("1001"); - Assert.assertEquals(subscriber.getModuleName(), "test2", "Updating subscriber has failed."); - } - - @Test(groups = "wso2.is", description = "Check deleting subscriber", dependsOnMethods = "testUpdateSubscriber") - public void testDeleteSubscriber() throws Exception { - - entitlementPolicyClient.deleteSubscriber("1001"); - Assert.assertNull(entitlementPolicyClient.getSubscriber("1001")); - } -} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/entitlement/EntitlementRestServiceTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/entitlement/EntitlementRestServiceTestCase.java deleted file mode 100644 index be99fa2b8fa..00000000000 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/entitlement/EntitlementRestServiceTestCase.java +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * you may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.identity.integration.test.entitlement; - -import org.apache.commons.codec.binary.Base64; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpHeaders; -import org.apache.http.HttpResponse; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.HttpClientBuilder; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.json.simple.JSONValue; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.carbon.identity.entitlement.stub.dto.PolicyDTO; -import org.wso2.identity.integration.common.clients.entitlement.EntitlementPolicyServiceClient; -import org.wso2.identity.integration.common.utils.ISIntegrationTest; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; - -/** - * This class includes test cases for Entitlement REST APIs. - */ -public class EntitlementRestServiceTestCase extends ISIntegrationTest { - - private static final Log log = LogFactory.getLog(EntitlementRestServiceTestCase.class); - private static final String ENDPOINT = "https://localhost:%s/api/identity/entitlement/decision/%s"; - public static final String CONTENT_TYPE_APPLICATION_JSON = "application/json"; - private static final String POLICY_ID = "urn:oasis:names:tc:xacml:3.0:custompolicy"; - private static final String POLICY = "read"; - private EntitlementPolicyServiceClient entitlementPolicyClient; - private HttpClient httpClient; - private String username; - private String password; - private String serverPort; - - @BeforeClass(alwaysRun = true) - public void testInit() throws Exception { - - super.init(); - entitlementPolicyClient = new EntitlementPolicyServiceClient(backendURL, sessionCookie); - httpClient = HttpClientBuilder.create().build(); - - serverPort = isServer.getDefaultInstance().getPorts().get("https"); - username = isServer.getContextTenant().getContextUser().getUserName(); - password = isServer.getContextTenant().getContextUser().getPassword(); - - } - - @AfterClass(alwaysRun = true) - public void testEnd() throws Exception { - - entitlementPolicyClient.publishPolicies(new String[]{POLICY_ID}, new String[]{"PDP " + - "Subscriber"}, "DELETE", true, null, 1); - entitlementPolicyClient.removePolicy(POLICY_ID); - entitlementPolicyClient = null; - httpClient = null; - } - - @Test(groups = "wso2.is", description = "Test retrieving API resource list") - public void testGetAPIResourceList() throws IOException { - - HttpGet getRequest = new HttpGet(String.format(ENDPOINT, serverPort, "home")); - getRequest.setHeader(HttpHeaders.AUTHORIZATION, getAuthzHeader()); - getRequest.setHeader(HttpHeaders.CONTENT_TYPE, CONTENT_TYPE_APPLICATION_JSON); - getRequest.setHeader(HttpHeaders.ACCEPT, CONTENT_TYPE_APPLICATION_JSON); - - HttpResponse response = httpClient.execute(getRequest); - - assertEquals(response.getStatusLine().getStatusCode(), 200, "Response for API resource list request failed"); - - try (BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) { - - Object responseObj = JSONValue.parse(rd); - assertNotNull(responseObj, "Cannot parse JSON response for API resource list request"); - - Object resourcesObj = ((JSONObject) responseObj).get("resources"); - assertNotNull(resourcesObj, "Response for API resource list request does not include 'resources'"); - - Object pdpResourceObj = ((JSONArray) resourcesObj).get(0); - assertNotNull(resourcesObj, "Response for API resource list request includes an empty set of 'resources'"); - - String linkRelation = ((JSONObject) pdpResourceObj).get("rel").toString(); - assertEquals(linkRelation, "http://docs.oasis-open.org/ns/xacml/relation/pdp", "Response for API " + - "resource" + " list request does not include 'pdp' resource"); - } - - getRequest.releaseConnection(); - } - - @Test(groups = "wso2.is", dependsOnMethods = {"testGetAPIResourceList"}, description = "Test policy publish") - public void testPublishPolicy() throws Exception { - - PolicyDTO policy = new PolicyDTO(); - policy.setPolicy(POLICY); - policy.setPolicy(policy.getPolicy().replaceAll(">\\s+<", "><").trim()); - policy.setVersion("3.0"); - policy.setPolicyId(POLICY_ID); - - log.info("XACML Policy:\n" + policy.getPolicy()); - entitlementPolicyClient.addPolicy(policy); - PolicyDTO updatedPolicy = entitlementPolicyClient.getPolicy(POLICY_ID, false); - assertNotNull(updatedPolicy, "Policy not added"); - - entitlementPolicyClient.publishPolicies(new String[]{POLICY_ID}, new String[]{"PDP Subscriber"}, "CREATE", - true, null, 1); - PolicyDTO publishedPolicy = entitlementPolicyClient.getPolicy(POLICY_ID, true); - assertNotNull(publishedPolicy, "Policy not published"); - } - - @Test(groups = "wso2.is", dependsOnMethods = {"testPublishPolicy"}, description = "Test get decision") - public void testGetDecision() throws Exception { - - HttpPost postRequest = new HttpPost(String.format(ENDPOINT, serverPort, "pdp")); - postRequest.setHeader(HttpHeaders.AUTHORIZATION, getAuthzHeader()); - postRequest.setHeader(HttpHeaders.CONTENT_TYPE, CONTENT_TYPE_APPLICATION_JSON); - postRequest.setHeader(HttpHeaders.ACCEPT, CONTENT_TYPE_APPLICATION_JSON); - - JSONObject subjectAttributeObj = new JSONObject(); - subjectAttributeObj.put("AttributeId", "urn:oasis:names:tc:xacml:1.0:subject:subject-id"); - subjectAttributeObj.put("Value", username); - - JSONArray subjectAttributeArray = new JSONArray(); - subjectAttributeArray.add(subjectAttributeObj); - - JSONObject subjectObj = new JSONObject(); - subjectObj.put("Attribute", subjectAttributeArray); - - JSONObject actionAttributeObj = new JSONObject(); - actionAttributeObj.put("AttributeId", "urn:oasis:names:tc:xacml:1.0:action:action-id"); - actionAttributeObj.put("Value", "read"); - - JSONArray actionAttributeArray = new JSONArray(); - actionAttributeArray.add(actionAttributeObj); - - JSONObject actionObj = new JSONObject(); - actionObj.put("Attribute", actionAttributeArray); - - JSONObject resourceAttributeObj = new JSONObject(); - resourceAttributeObj.put("AttributeId", "urn:oasis:names:tc:xacml:1.0:resource:resource-id"); - resourceAttributeObj.put("Value", "http://test.com/service/very_secure/"); - - JSONArray resourceAttributeArray = new JSONArray(); - resourceAttributeArray.add(resourceAttributeObj); - - JSONObject resourceObj = new JSONObject(); - resourceObj.put("Attribute", resourceAttributeArray); - - JSONObject requestObj = new JSONObject(); - requestObj.put("AccessSubject", subjectObj); - requestObj.put("Action", actionObj); - requestObj.put("Resource", resourceObj); - - JSONObject rootObj = new JSONObject(); - rootObj.put("Request", requestObj); - - String request = rootObj.toJSONString(); - log.info("XACML Request:\n" + request); - - StringEntity entity = new StringEntity(request); - postRequest.setEntity(entity); - - Thread.sleep(5000); - - HttpResponse response = httpClient.execute(postRequest); - - assertEquals(response.getStatusLine().getStatusCode(), 200, "Response for PDP decision request failed"); - - try (BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) { - - Object responseObj = JSONValue.parse(rd); - assertNotNull(responseObj, "Cannot parse JSON response for PDP decision request"); - - log.info("XACML Response:\n" + responseObj.toString()); - - Object pdpResponseObj = ((JSONObject) responseObj).get("Response"); - assertNotNull(pdpResponseObj, "Response for PDP decision request does not include 'Response'"); - - Object pdpDecisionObj = ((JSONArray) pdpResponseObj).get(0); - assertNotNull(pdpResponseObj, "Response for PDP decision request includes an empty set of 'decisions'"); - - String decision = ((JSONObject) pdpDecisionObj).get("Decision").toString(); - assertEquals(decision, "Permit", "Response for PDP decision request does not return 'Permit'"); - } - - postRequest.releaseConnection(); - } - - private String getAuthzHeader() { - return "Basic " + Base64.encodeBase64String((username + ":" + password).getBytes()).trim(); - } -} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/entitlement/EntitlementSecurityTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/entitlement/EntitlementSecurityTestCase.java deleted file mode 100644 index e5b6aa71114..00000000000 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/entitlement/EntitlementSecurityTestCase.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.identity.integration.test.entitlement; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.URLEncoder; - -import junit.framework.Assert; -import org.apache.http.HttpResponse; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.commons.lang.StringEscapeUtils; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.identity.integration.common.utils.ISIntegrationTest; - -import javax.servlet.http.HttpServletResponse; - -public class EntitlementSecurityTestCase extends ISIntegrationTest { - private HttpClient httpClient; - private String value; - private String url; - - @BeforeClass(alwaysRun = true) - public void testInit() throws Exception { - super.init(); - httpClient = HttpClientBuilder.create().build(); - value = ""; - String encodedValue = URLEncoder.encode(value, "UTF-8"); - String temp = backendURL.replaceAll("services/","carbon/policyeditor/prettyPrinter_ajaxprocessor.jsp?xmlString="); - url = temp + encodedValue; - } - - @AfterClass(alwaysRun = true) - public void atEnd() throws Exception { - httpClient = null; - } - - @Test(alwaysRun = true, description = "Test reflected XSS in XACML policy editor") - public void testXSS() throws IOException { - HttpGet request = new HttpGet(url); - HttpResponse response = httpClient.execute(request); - - // If HTTP status code is 200... - if (response.getStatusLine().getStatusCode() == HttpServletResponse.SC_OK) { - BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); - String line; - boolean success = false; - while ((line = rd.readLine()) != null) { - success = line.equals(StringEscapeUtils.escapeHtml(value)); - if (success){ - break; - } - } - - rd.close(); - - if(success) { - Assert.fail("Content is not encoded"); - } - } - - // If HTTP status code is 405... - else if (response.getStatusLine().getStatusCode() == HttpServletResponse.SC_METHOD_NOT_ALLOWED){ - log.info("GET request to XACML policy editor is blocked as expected"); - } - - // If HTTP status code is neither 200 nor 405... - else { - log.info("Unknown response"); - } - } -} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/entitlement/EntitlementServiceTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/entitlement/EntitlementServiceTestCase.java deleted file mode 100644 index 44c96c864f3..00000000000 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/entitlement/EntitlementServiceTestCase.java +++ /dev/null @@ -1,154 +0,0 @@ -/** - * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.wso2.identity.integration.test.entitlement; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.identity.integration.common.clients.UserProfileMgtServiceClient; -import org.wso2.identity.integration.common.clients.entitlement.EntitlementPolicyServiceClient; -import org.wso2.identity.integration.common.clients.entitlement.EntitlementServiceClient; -import org.wso2.carbon.identity.entitlement.stub.EntitlementPolicyAdminServiceEntitlementException; -import org.wso2.carbon.identity.entitlement.stub.EntitlementServiceException; -import org.wso2.carbon.identity.entitlement.stub.dto.PolicyDTO; -import org.wso2.identity.integration.common.utils.ISIntegrationTest; -import org.wso2.carbon.identity.user.profile.stub.UserProfileMgtServiceUserProfileExceptionException; -import org.wso2.carbon.identity.user.profile.stub.types.UserFieldDTO; -import org.wso2.carbon.identity.user.profile.stub.types.UserProfileDTO; - -import java.rmi.RemoteException; - -public class EntitlementServiceTestCase extends ISIntegrationTest { - private static final Log log = LogFactory.getLog(EntitlementServiceTestCase.class); - private EntitlementServiceClient entitlementServiceClient; - private EntitlementPolicyServiceClient entitlementPolicyClient; - private UserProfileMgtServiceClient userProfileMgtClient; - - private static final String REQUEST = "" + - "" + - "" + - "read" + - "" + - "" + - "admin" + - "" + - "" + - "http://localhost:8280/services/echo/" + - ""; - private static final String POLICY_ID = "urn:oasis:names:tc:xacml:3.0:custompolicy"; - private static final String POLICY = "" + - "sample policy" + - "" + - "http://localhost:8280/services/echo/" + - "" + - "read" + - "" + - "" + - "SL" + - ""; - - - @BeforeClass(alwaysRun = true) - public void testInit() throws Exception { - super.init(); - entitlementPolicyClient = new EntitlementPolicyServiceClient(backendURL, sessionCookie); - entitlementServiceClient = new EntitlementServiceClient(backendURL, sessionCookie); - userProfileMgtClient = new UserProfileMgtServiceClient(backendURL, sessionCookie); - } - - @Test(groups = "wso2.is", description = "Check set user profile") - public void testSetUserProfile() throws RemoteException, UserProfileMgtServiceUserProfileExceptionException { - UserProfileDTO profile = userProfileMgtClient.getUserProfile("admin", "default"); - UserFieldDTO country = new UserFieldDTO(); - country.setClaimUri("http://wso2.org/claims/country"); - country.setFieldValue("SL"); - UserFieldDTO[] fields = profile.getFieldValues(); - UserFieldDTO[] newfields = new UserFieldDTO[fields.length]; - for (int i=0; i\\s+<", "><").trim()); - policy.setVersion("3.0"); - policy.setPolicyId(POLICY_ID); - Thread.sleep(10000); //waiting till server gets ready - entitlementPolicyClient.addPolicy(policy); - Thread.sleep(5000); // waiting for the policy to deploy - entitlementPolicyClient.publishPolicies(new String[]{POLICY_ID}, new String[]{"PDP Subscriber"}, "CREATE", true, null, 1); - Assert.assertNotNull(entitlementPolicyClient.getPolicy(POLICY_ID, true), "Entitlement service publish policy failed."); - } - - @Test(groups = "wso2.is", dependsOnMethods = {"testPublishPolicy"}, description = "Check get decision") - public void testGetDecision() throws EntitlementServiceException, RemoteException, - EntitlementPolicyAdminServiceEntitlementException { - String decision = entitlementServiceClient.getDecision(REQUEST); - log.info(decision); - Assert.assertTrue(decision.contains("Permit"), "Entitlement service get decision failed."); - } - - @Test(groups = "wso2.is", dependsOnMethods = {"testPublishPolicy"}, description = "Check get decision by attributes") - public void testGetDecisionByAttributes() throws EntitlementServiceException, RemoteException { - String decision = entitlementServiceClient.getDecisionByAttributes("admin", "http://localhost:8280/services/echo/", "read", null); - log.info(decision); - Assert.assertTrue(decision.contains("Permit"), "Entitlement service get decision failed."); - } - - @Test(groups = "wso2.is", dependsOnMethods = {"testGetDecisionByAttributes"}, description = "Check get decision deny state") - public void testGetDecisionDenyState() throws Exception { - UserProfileDTO profile = userProfileMgtClient.getUserProfile("admin", "default"); - UserFieldDTO country = new UserFieldDTO(); - country.setClaimUri("http://wso2.org/claims/country"); - country.setFieldValue("USA"); - UserFieldDTO[] fields = profile.getFieldValues(); - UserFieldDTO[] newfields = new UserFieldDTO[fields.length]; - for (int i = 0; i < fields.length; i++) { - if (fields[i].getDisplayName().toString().equals("Country")) { - newfields[i] = country; - } else { - newfields[i] = fields[i]; - } - } - profile.setFieldValues(newfields); - userProfileMgtClient.setUserProfile("admin", profile); - Thread.sleep(5000); - String decision = entitlementServiceClient.getDecisionByAttributes("admin", "http://localhost:8280/services/echo/", "read", null); - log.info(decision); - Assert.assertTrue(decision.contains("Deny"), "Entitlement service get decision failed."); - } -} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/idp/mgt/PreferenceAPIIntegrationUITestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/idp/mgt/PreferenceAPIIntegrationUITestCase.java index d306d9c941b..08b5cc77f53 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/idp/mgt/PreferenceAPIIntegrationUITestCase.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/idp/mgt/PreferenceAPIIntegrationUITestCase.java @@ -53,6 +53,8 @@ public class PreferenceAPIIntegrationUITestCase extends OAuth2ServiceAbstractInt private static final String ENABLE_SELF_REGISTRATION_PROP_KEY = "SelfRegistration.Enable"; private static final String ENABLE_USERNAME_RECOVERY_PROP_KEY = "Recovery.Notification.Username.Enable"; + private static final String ENABLE_USERNAME_EMAIL_RECOVERY_PROP_KEY = "Recovery.Notification.Username.Email.Enable"; + private static final String ENABLE_USERNAME_SMS_RECOVERY_PROP_KEY = "Recovery.Notification.Username.SMS.Enable"; private static final String ENABLE_PASSWORD_QS_RECOVERY_PROP_KEY = "Recovery.Question.Password.Enable"; private static final String ENABLE_PASSWORD_NOTIFICATION_RECOVERY_PROP_KEY = "Recovery.Notification.Password.Enable"; @@ -129,6 +131,8 @@ public void resetResidentIDP() throws Exception { updateResidentIDPProperties(superTenantResidentIDP, Map.of( ENABLE_SELF_REGISTRATION_PROP_KEY, "false", ENABLE_USERNAME_RECOVERY_PROP_KEY, "false", + ENABLE_USERNAME_EMAIL_RECOVERY_PROP_KEY, "false", + ENABLE_USERNAME_SMS_RECOVERY_PROP_KEY, "false", ENABLE_PASSWORD_QS_RECOVERY_PROP_KEY, "false", ENABLE_PASSWORD_NOTIFICATION_RECOVERY_PROP_KEY, "false", ENABLE_PASSWORD_EMAIL_LINK_RECOVERY_PROP_KEY, "false", @@ -155,7 +159,10 @@ public void testSelfRegistration() throws Exception { @Test(groups = "wso2.is", description = "Check Username recovery Login Page") public void testUsernameRecovery() throws Exception { - updateResidentIDPProperty(superTenantResidentIDP, ENABLE_USERNAME_RECOVERY_PROP_KEY, "true"); + updateResidentIDPProperties(superTenantResidentIDP, Map.of( + ENABLE_USERNAME_EMAIL_RECOVERY_PROP_KEY, "true", + ENABLE_USERNAME_RECOVERY_PROP_KEY, "true" + )); String content = sendAuthorizeRequest(); Assert.assertTrue(content.contains(RECOVERY_USERNAME_CONTENT)); } diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oauth2/JITUserAssociationTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oauth2/JITUserAssociationTestCase.java new file mode 100644 index 00000000000..286f669a2c4 --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oauth2/JITUserAssociationTestCase.java @@ -0,0 +1,853 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.identity.integration.test.oauth2; + +import com.nimbusds.oauth2.sdk.AuthorizationCode; +import com.nimbusds.oauth2.sdk.AuthorizationCodeGrant; +import com.nimbusds.oauth2.sdk.TokenErrorResponse; +import com.nimbusds.oauth2.sdk.TokenRequest; +import com.nimbusds.oauth2.sdk.TokenResponse; +import com.nimbusds.oauth2.sdk.auth.ClientSecretBasic; +import com.nimbusds.oauth2.sdk.auth.Secret; +import com.nimbusds.oauth2.sdk.http.HTTPResponse; +import com.nimbusds.oauth2.sdk.id.ClientID; +import com.nimbusds.openid.connect.sdk.OIDCTokenResponse; +import com.nimbusds.openid.connect.sdk.OIDCTokenResponseParser; +import com.nimbusds.openid.connect.sdk.token.OIDCTokens; +import io.restassured.http.ContentType; +import io.restassured.response.ExtractableResponse; +import io.restassured.response.Response; +import org.apache.commons.lang.StringUtils; +import org.apache.http.Header; +import org.apache.http.HttpHeaders; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.NameValuePair; +import org.apache.http.client.CookieStore; +import org.apache.http.client.HttpClient; +import org.apache.http.client.config.CookieSpecs; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.config.Lookup; +import org.apache.http.config.RegistryBuilder; +import org.apache.http.cookie.CookieSpecProvider; +import org.apache.http.impl.client.BasicCookieStore; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.cookie.RFC6265CookieSpecProvider; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.util.EntityUtils; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; +import org.wso2.carbon.automation.engine.context.AutomationContext; +import org.wso2.carbon.automation.engine.context.TestUserMode; +import org.wso2.carbon.integration.common.utils.exceptions.AutomationUtilException; +import org.wso2.carbon.integration.common.utils.mgt.ServerConfigurationManager; +import org.wso2.identity.integration.test.application.mgt.AbstractIdentityFederationTestCase; +import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.AdvancedApplicationConfiguration; +import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.ApplicationModel; +import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.ApplicationResponseModel; +import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.AuthenticationSequence; +import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.AuthenticationSequence.TypeEnum; +import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.Authenticator; +import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.Claim; +import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.ClaimConfiguration; +import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.InboundProtocols; +import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.OpenIDConnectConfiguration; +import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.RequestedClaimConfiguration; +import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.SubjectConfig; +import org.wso2.identity.integration.test.rest.api.server.idp.v1.model.FederatedAuthenticatorRequest; +import org.wso2.identity.integration.test.rest.api.server.idp.v1.model.FederatedAuthenticatorRequest.FederatedAuthenticator; +import org.wso2.identity.integration.test.rest.api.server.idp.v1.model.IdentityProviderPOSTRequest; +import org.wso2.identity.integration.test.rest.api.server.idp.v1.model.ProvisioningRequest; +import org.wso2.identity.integration.test.rest.api.server.idp.v1.model.ProvisioningRequest.JustInTimeProvisioning; +import org.wso2.identity.integration.test.rest.api.user.common.model.Name; +import org.wso2.identity.integration.test.rest.api.user.common.model.UserObject; +import org.wso2.identity.integration.test.restclients.SCIM2RestClient; +import org.wso2.identity.integration.test.util.Utils; +import org.wso2.identity.integration.test.utils.DataExtractUtil; +import org.wso2.identity.integration.test.utils.IdentityConstants; +import org.wso2.identity.integration.test.utils.OAuth2Constant; + +import javax.xml.xpath.XPathExpressionException; +import java.io.File; +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static io.restassured.RestAssured.given; +import static org.wso2.identity.integration.test.applicationNativeAuthentication.Constants.ADDITIONAL_DATA; +import static org.wso2.identity.integration.test.applicationNativeAuthentication.Constants.AUTHENTICATOR; +import static org.wso2.identity.integration.test.applicationNativeAuthentication.Constants.AUTHENTICATORS; +import static org.wso2.identity.integration.test.applicationNativeAuthentication.Constants.AUTHENTICATOR_ID; +import static org.wso2.identity.integration.test.applicationNativeAuthentication.Constants.AUTH_DATA_CODE; +import static org.wso2.identity.integration.test.applicationNativeAuthentication.Constants.AUTH_DATA_SESSION_STATE; +import static org.wso2.identity.integration.test.applicationNativeAuthentication.Constants.CONTENT_TYPE_APPLICATION_JSON; +import static org.wso2.identity.integration.test.applicationNativeAuthentication.Constants.FLOW_ID; +import static org.wso2.identity.integration.test.applicationNativeAuthentication.Constants.FLOW_STATUS; +import static org.wso2.identity.integration.test.applicationNativeAuthentication.Constants.FLOW_TYPE; +import static org.wso2.identity.integration.test.applicationNativeAuthentication.Constants.HREF; +import static org.wso2.identity.integration.test.applicationNativeAuthentication.Constants.IDP; +import static org.wso2.identity.integration.test.applicationNativeAuthentication.Constants.LINKS; +import static org.wso2.identity.integration.test.applicationNativeAuthentication.Constants.METADATA; +import static org.wso2.identity.integration.test.applicationNativeAuthentication.Constants.NEXT_STEP; +import static org.wso2.identity.integration.test.applicationNativeAuthentication.Constants.PROMPT_TYPE; +import static org.wso2.identity.integration.test.applicationNativeAuthentication.Constants.REDIRECT_URL; +import static org.wso2.identity.integration.test.applicationNativeAuthentication.Constants.REQUIRED_PARAMS; +import static org.wso2.identity.integration.test.applicationNativeAuthentication.Constants.RESPONSE_MODE; +import static org.wso2.identity.integration.test.applicationNativeAuthentication.Constants.STATE; +import static org.wso2.identity.integration.test.applicationNativeAuthentication.Constants.STEP_TYPE; +import static org.wso2.identity.integration.test.applicationNativeAuthentication.Constants.SUCCESS_COMPLETED; +import static org.wso2.identity.integration.test.applicationNativeAuthentication.Constants.UTF_8; + +/** + * Integration test cases for verifying user association behavior after Just-in-Time (JIT) provisioning. + * This test suite checks the server's response to the presence or absence of the following configuration: + * ```toml + * [authentication.jit_provisioning] + * associating_to_existing_user = "true" + * ``` + * This configuration controls whether newly provisioned users are associated with existing users + * during the JIT provisioning process. + */ +public class JITUserAssociationTestCase extends AbstractIdentityFederationTestCase { + + private static final String PRIMARY_IS_SP_NAME = "travelocity"; + private static final String PRIMARY_IS_IDP_NAME = "trustedIdP"; + private static final String PRIMARY_IS_IDP_AUTHENTICATOR_NAME_OIDC = "OpenIDConnectAuthenticator"; + // AUTHENTICATOR_ID is base64URLEncode of PRIMARY_IS_IDP_AUTHENTICATOR_NAME_OIDC:PRIMARY_IS_IDP_NAME + private static final String FEDERATE_AUTHENTICATOR_ID = "T3BlbklEQ29ubmVjdEF1dGhlbnRpY2F0b3I6dHJ1c3RlZElkUA"; + private static final String ENCODED_PRIMARY_IS_IDP_AUTHENTICATOR_ID_OIDC = "T3BlbklEQ29ubmVjdEF1dGhlbnRpY2F0b3I"; + private static final String PRIMARY_IS_IDP_CALLBACK_URL = "https://localhost:9853/commonauth"; + private static final String PRIMARY_IS_TOKEN_URL = "https://localhost:9853/oauth2/token"; + private static final String SECONDARY_IS_TEST_USERNAME = "testFederatedUser"; + private static final String SECONDARY_IS_TEST_PASSWORD = "TestFederatePassword@123"; + private static final String SECONDARY_IS_SP_NAME = "secondarySP"; + private static final String SECONDARY_IS_IDP_CALLBACK_URL = "https://localhost:9854/commonauth"; + private static final String SECONDARY_IS_TOKEN_ENDPOINT = "https://localhost:9854/oauth2/token"; + private static final String SECONDARY_IS_LOGOUT_ENDPOINT = "https://localhost:9854/oidc/logout"; + private static final String SECONDARY_IS_AUTHORIZE_ENDPOINT = "https://localhost:9854/oauth2/authorize"; + private static final String HTTPS_LOCALHOST_SERVICES = "https://localhost:%s/"; + private static final String NAME_KEY = "name"; + private static final String GIVEN_NAME_KEY = "givenName"; + private static final String FAMILY_NAME_KEY = "familyName"; + private static final String LOCAL_GIVEN_NAME = "localUserGivenName"; + private static final String LOCAL_FAMILY_NAME = "localUserFamilyName"; + private static final String FEDERATED_GIVEN_NAME = "localUserGivenName"; + private static final String FEDERATED_FAMILY_NAME = "localUserFamilyName"; + private String secondaryISAppId; + private String secondaryISClientID; + private String secondaryISClientSecret; + private String appClientID; + private String appClientSecret; + private String username; + private String userPassword; + private AutomationContext context; + + private String flowId; + private String flowStatus; + private String authenticatorId; + private String href; + private String redirectURL; + private String nonce; + private String state; + private String code; + private static final int PORT_OFFSET_0 = 0; + private static final int PORT_OFFSET_1 = 1; + CookieStore cookieStore; + private CloseableHttpClient client; + private String primaryISIdpId; + private String primaryISAppId; + private SCIM2RestClient primaryISScim2RestClient; + private SCIM2RestClient secondaryISScim2RestClient; + private String secondaryISUserId; + private String primaryISUserId; + private ServerConfigurationManager serverConfigurationManager; + + + @DataProvider(name = "configProvider") + public static Object[][] configProvider() { + + return new Object[][]{{TestUserMode.SUPER_TENANT_ADMIN}}; + } + + @Factory(dataProvider = "configProvider") + public JITUserAssociationTestCase(TestUserMode userMode) throws Exception { + + context = new AutomationContext("IDENTITY", userMode); + this.username = context.getContextTenant().getTenantAdmin().getUserName(); + this.userPassword = context.getContextTenant().getTenantAdmin().getPassword(); + } + + @BeforeClass(alwaysRun = true) + public void initTest() throws Exception { + + super.initTest(); + changeISConfiguration(); + createServiceClients(PORT_OFFSET_0, new IdentityConstants.ServiceClientType[]{ + IdentityConstants.ServiceClientType.APPLICATION_MANAGEMENT, + IdentityConstants.ServiceClientType.IDENTITY_PROVIDER_MGT}); + + createServiceClients(PORT_OFFSET_1, new IdentityConstants.ServiceClientType[]{ + IdentityConstants.ServiceClientType.APPLICATION_MANAGEMENT}); + + createApplicationInSecondaryIS(); + createIDPInPrimaryIS(); + createApplicationInPrimaryIS(); + + secondaryISScim2RestClient = new SCIM2RestClient(getSecondaryISURI(), tenantInfo); + primaryISScim2RestClient = new SCIM2RestClient(getPrimaryISURI(), tenantInfo); + addUserToPrimaryIS(); + addUserToSecondaryIS(); + } + + @BeforeMethod(alwaysRun = true) + public void initTestRun() { + + cookieStore = new BasicCookieStore(); + Lookup cookieSpecRegistry = RegistryBuilder.create() + .register(CookieSpecs.DEFAULT, new RFC6265CookieSpecProvider()).build(); + RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build(); + client = HttpClientBuilder.create().setDefaultCookieSpecRegistry(cookieSpecRegistry) + .setDefaultRequestConfig(requestConfig).setDefaultCookieStore(cookieStore).build(); + } + + @AfterClass(alwaysRun = true) + public void endTest() throws Exception { + + try { + deleteApplication(PORT_OFFSET_0, primaryISAppId); + deleteIdp(PORT_OFFSET_0, primaryISIdpId); + deleteApplication(PORT_OFFSET_1, secondaryISAppId); + + deleteAddedUsersInSecondaryIS(); + deleteAddedUsersInPrimaryIS(); + // Nullifying attributes. + secondaryISAppId = null; + secondaryISClientID = null; + secondaryISClientSecret = null; + appClientID = null; + appClientSecret = null; + username = null; + userPassword = null; + context = null; + + // Application Native Authentication related attributes + flowId = null; + flowStatus = null; + authenticatorId = null; + href = null; + redirectURL = null; + nonce = null; + state = null; + code = null; + + client.close(); + secondaryISScim2RestClient.closeHttpClient(); + primaryISScim2RestClient.closeHttpClient(); + } catch (Exception e) { + log.error("Failure occured due to :" + e.getMessage(), e); + throw e; + } + } + + private void resetISConfiguration() throws Exception { + + log.info("Replacing deployment.toml with default configurations"); + serverConfigurationManager.restoreToLastConfiguration(true); + } + + + @Test(groups = "wso2.is", description = "Send init authorize POST request to primary IDP.") + public void testJITProvisioningWithAssociation() throws Exception { + executeAuthorizationAndTokenRetrieval(FEDERATED_GIVEN_NAME, FEDERATED_FAMILY_NAME); + } + + @Test(groups = "wso2.is", description = "Send init authorize POST request to primary IDP.", + dependsOnMethods = "testJITProvisioningWithAssociation") + public void testJITProvisioningWithoutAssociation() throws Exception { + resetISConfiguration(); + deleteAddedUsersInPrimaryIS(); + addUserToPrimaryIS(); + executeAuthorizationAndTokenRetrieval(LOCAL_GIVEN_NAME, LOCAL_FAMILY_NAME); + } + + private void executeAuthorizationAndTokenRetrieval(String expectedGivenName, String expectedFamilyName) throws Exception { + // Send init authorize POST request to primary IDP + authorizePrimaryIDP(); + + // Send authorization request to federated IDP and retrieve code. + authorizeFederatedIDP(); + + // Send authentication POST request with code and state retrieved from federated IDP + authenticatePrimaryIDPWithFederatedResponse(); + + // Send get access token request. + TokenRequest tokenReq = getTokenRequest(); + + HTTPResponse tokenHTTPResp = tokenReq.toHTTPRequest().send(); + Assert.assertNotNull(tokenHTTPResp, "Access token http response is null."); + + TokenResponse tokenResponse = OIDCTokenResponseParser.parse(tokenHTTPResp); + Assert.assertNotNull(tokenResponse, "Access token response is null."); + + Assert.assertFalse(tokenResponse instanceof TokenErrorResponse, + "Access token response contains errors."); + + OIDCTokenResponse oidcTokenResponse = (OIDCTokenResponse) tokenResponse; + OIDCTokens oidcTokens = oidcTokenResponse.getOIDCTokens(); + + Assert.assertNotNull(oidcTokens, "OIDC Tokens object is null."); + + String idToken = oidcTokens.getIDTokenString(); + Assert.assertNotNull(idToken, "ID token is null"); + + JSONObject userParameters = primaryISScim2RestClient.getUser(primaryISUserId, null); + JSONObject name = (JSONObject) userParameters.get(NAME_KEY); + String givenName = (String) name.get(GIVEN_NAME_KEY); + String familyName = (String) name.get(FAMILY_NAME_KEY); + + Assert.assertEquals(givenName, expectedGivenName, "First name claim didn't get populated correctly."); + Assert.assertEquals(familyName, expectedFamilyName, "Last name claim didn't get populated correctly."); + } + + private TokenRequest getTokenRequest() throws URISyntaxException { + + ClientID clientID = new ClientID(appClientID); + Secret clientSecret = new Secret(appClientSecret); + ClientSecretBasic clientSecretBasic = new ClientSecretBasic(clientID, clientSecret); + + URI callbackURI = new URI(PRIMARY_IS_IDP_CALLBACK_URL); + AuthorizationCode authorizationCode = new AuthorizationCode(code); + AuthorizationCodeGrant authorizationCodeGrant = new AuthorizationCodeGrant(authorizationCode, callbackURI); + + return new TokenRequest(new URI(PRIMARY_IS_TOKEN_URL), clientSecretBasic, + authorizationCodeGrant); + } + + private void authorizePrimaryIDP() + throws IOException, ParseException, URISyntaxException { + + HttpResponse primaryISAuthorizePOSTResponse = + sendPostRequestWithParameters(client, buildOAuth2Parameters(appClientID + ), OAuth2Constant.AUTHORIZE_ENDPOINT_URL); + Assert.assertNotNull(primaryISAuthorizePOSTResponse, + "Authorization request failed. Authorized response is null."); + + JSONObject json = getJsonObject(primaryISAuthorizePOSTResponse); + Assert.assertNotNull(json, "Client Native Authentication Init response is null."); + + validInitClientNativeAuthnResponse(json); + } + + private void authenticatePrimaryIDPWithFederatedResponse() { + + String body = generateAuthReqBody(); + + Response primaryISAuthenticationResponse = getResponseOfJSONPost(href, body, new HashMap<>()); + ExtractableResponse extractableResponse = primaryISAuthenticationResponse.then() + .log().ifValidationFails() + .assertThat() + .statusCode(HttpStatus.SC_OK) + .and() + .assertThat() + .header(HttpHeaders.CONTENT_TYPE, CONTENT_TYPE_APPLICATION_JSON) + .extract(); + Assert.assertNotNull(extractableResponse, "Federated Authentication failed. Authentication response is null."); + + validateAuthenticationResponseBody(extractableResponse); + } + + private void authorizeFederatedIDP() throws IOException, URISyntaxException { + + HttpResponse federatedIDPAuthorizeResponse = + sendPostRequestWithParameters(client, getNameValuePairsForExternalFederation(), + SECONDARY_IS_AUTHORIZE_ENDPOINT); + Assert.assertNotNull(federatedIDPAuthorizeResponse, + "Authorization request failed. Authorized response is null."); + + validateSecondaryISFederationResponse(federatedIDPAuthorizeResponse); + } + + /** + * Invoke given endpointUri for JSON POST request with given body, headers and Basic authentication, authentication + * credential being the authenticatingUserName and authenticatingCredential. + * + * @param endpointUri endpoint to be invoked + * @param body payload + * @param headers list of headers to be added to the request + * @return response + */ + protected Response getResponseOfJSONPost(String endpointUri, String body, Map headers) { + + return given() + .contentType(ContentType.JSON) + .headers(headers) + .body(body) + .when() + .post(endpointUri); + } + + /** + * Validates specific fields in the JSON response of a basic authentication response. + * + * @param extractableResponse The ExtractableResponse containing the JSON response + */ + private void validateAuthenticationResponseBody(ExtractableResponse extractableResponse) { + + // Validate specific fields in the JSON response + flowStatus = extractableResponse + .jsonPath() + .getString(FLOW_STATUS); + Assert.assertEquals(flowStatus, SUCCESS_COMPLETED); + + code = extractableResponse + .jsonPath() + .getString(AUTH_DATA_CODE); + Assert.assertNotNull(code, "Authorization Code is null in the authData"); + + Assert.assertNotNull(extractableResponse + .jsonPath() + .getString(AUTH_DATA_SESSION_STATE), "Session state is null in the authData"); + } + + /** + * Extract the location header value from a HttpResponse. + * + * @param response HttpResponse object that needs the header extracted. + * @return String value of the location header. + */ + private String getLocationHeaderValue(HttpResponse response) { + + Header location = response.getFirstHeader(OAuth2Constant.HTTP_RESPONSE_HEADER_LOCATION); + Assert.assertNotNull(location, "Location header is null."); + return location.getValue(); + } + + /** + * Send approval post request + * + * @param client - http client + * @param sessionDataKeyConsent - session consent data + * @return http response + * @throws IOException java.io.IOException + */ + private HttpResponse sendApprovalPost(HttpClient client, String sessionDataKeyConsent) + throws IOException { + + List urlParameters = new ArrayList<>(); + urlParameters.add(new BasicNameValuePair("sessionDataKey", sessionDataKeyConsent)); + + return sendPostRequestWithParameters(client, urlParameters, + getTenantQualifiedURL(SECONDARY_IS_AUTHORIZE_ENDPOINT, tenantInfo.getDomain())); + } + + private void addUserToSecondaryIS() throws Exception { + + UserObject user = new UserObject() + .userName(SECONDARY_IS_TEST_USERNAME) + .password(SECONDARY_IS_TEST_PASSWORD) + .name(new Name().givenName(FEDERATED_GIVEN_NAME).familyName(FEDERATED_FAMILY_NAME)); + + secondaryISUserId = secondaryISScim2RestClient.createUser(user); + Assert.assertNotNull(secondaryISUserId, "User creation failed in secondary IS."); + } + + private void addUserToPrimaryIS() throws Exception{ + UserObject user = new UserObject() + .userName(SECONDARY_IS_TEST_USERNAME) + .password(SECONDARY_IS_TEST_PASSWORD) + .name(new Name().givenName(LOCAL_GIVEN_NAME).familyName(LOCAL_FAMILY_NAME)); + + primaryISUserId = primaryISScim2RestClient.createUser(user); + Assert.assertNotNull(primaryISUserId, "User creation failed in primary IS."); + } + + private void deleteAddedUsersInSecondaryIS() throws IOException { + + secondaryISScim2RestClient.deleteUser(secondaryISUserId); + } + + private void deleteAddedUsersInPrimaryIS() throws IOException { + + primaryISScim2RestClient.deleteUser(primaryISUserId); + } + + protected String getSecondaryISURI() { + + return String.format(HTTPS_LOCALHOST_SERVICES, DEFAULT_PORT + PORT_OFFSET_1); + } + + protected String getPrimaryISURI() { + + return String.format(HTTPS_LOCALHOST_SERVICES, DEFAULT_PORT); + } + + private void createApplicationInPrimaryIS() throws Exception { + + + ApplicationModel applicationCreationModel = new ApplicationModel() + .name(PRIMARY_IS_SP_NAME) + .description("This is a test Service Provider") + .isManagementApp(true) + .inboundProtocolConfiguration(new InboundProtocols().oidc(getAppOIDCConfigurations())) + .authenticationSequence(new AuthenticationSequence() + .type(TypeEnum.USER_DEFINED) + .addStepsItem( + new org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.AuthenticationStep() + .id(1) + .addOptionsItem(new Authenticator() + .idp(PRIMARY_IS_IDP_NAME) + .authenticator(PRIMARY_IS_IDP_AUTHENTICATOR_NAME_OIDC)))) + .advancedConfigurations(new AdvancedApplicationConfiguration().enableAPIBasedAuthentication(true)); + + primaryISAppId = addApplication(PORT_OFFSET_0, applicationCreationModel); + ApplicationResponseModel application = getApplication(PORT_OFFSET_0, primaryISAppId); + Assert.assertNotNull(application, "Failed to create service provider 'travelocity' in primary IS"); + + OpenIDConnectConfiguration oidcConfig = getOIDCInboundDetailsOfApplication(PORT_OFFSET_0, primaryISAppId); + appClientID = oidcConfig.getClientId(); + Assert.assertNotNull(appClientID, + "Failed to update service provider with inbound OIDC configs in primary IS"); + appClientSecret = oidcConfig.getClientSecret(); + Assert.assertNotNull(appClientSecret, + "Failed to update service provider with inbound OIDC configs in primary IS"); + } + + private void createApplicationInSecondaryIS() throws Exception { + + ClaimConfiguration claimConfiguration = new ClaimConfiguration(); + claimConfiguration.setSubject(new SubjectConfig().claim(new Claim().uri("http://wso2.org/claims/username"))); + claimConfiguration.addRequestedClaimsItem(getRequestedClaim("http://wso2.org/claims/username")); + claimConfiguration.addRequestedClaimsItem(getRequestedClaim("http://wso2.org/claims/givenname")); + claimConfiguration.addRequestedClaimsItem(getRequestedClaim("http://wso2.org/claims/lastname")); + claimConfiguration.addRequestedClaimsItem(getRequestedClaim("http://wso2.org/claims/fullname")); + + ApplicationModel applicationCreationModel = new ApplicationModel() + .name(SECONDARY_IS_SP_NAME) + .description("This is a test Service Provider") + .isManagementApp(true) + .inboundProtocolConfiguration(new InboundProtocols().oidc(getSP2OIDCConfigurations())) + .advancedConfigurations( + new AdvancedApplicationConfiguration().skipLoginConsent(true).skipLogoutConsent(true)) + .claimConfiguration(claimConfiguration); + + secondaryISAppId = addApplication(PORT_OFFSET_1, applicationCreationModel); + Assert.assertNotNull(secondaryISAppId, "Failed to create service provider 'secondarySP' in secondary IS"); + + OpenIDConnectConfiguration oidcConfig = getOIDCInboundDetailsOfApplication(PORT_OFFSET_1, secondaryISAppId); + secondaryISClientID = oidcConfig.getClientId(); + Assert.assertNotNull(secondaryISClientID, + "Failed to update service provider with inbound OIDC configs in secondary IS"); + secondaryISClientSecret = oidcConfig.getClientSecret(); + Assert.assertNotNull(secondaryISClientSecret, + "Failed to update service provider with inbound OIDC configs in secondary IS"); + } + + private void createIDPInPrimaryIS() throws Exception { + + FederatedAuthenticator authenticator = new FederatedAuthenticator() + .authenticatorId(ENCODED_PRIMARY_IS_IDP_AUTHENTICATOR_ID_OIDC) + .name(PRIMARY_IS_IDP_AUTHENTICATOR_NAME_OIDC) + .isEnabled(true) + .addProperty(new org.wso2.identity.integration.test.rest.api.server.idp.v1.model.Property() + .key(IdentityConstants.Authenticator.OIDC.IDP_NAME) + .value("oidcFedIdP")) + .addProperty(new org.wso2.identity.integration.test.rest.api.server.idp.v1.model.Property() + .key(IdentityConstants.Authenticator.OIDC.CLIENT_ID) + .value(secondaryISClientID)) + .addProperty(new org.wso2.identity.integration.test.rest.api.server.idp.v1.model.Property() + .key(IdentityConstants.Authenticator.OIDC.CLIENT_SECRET) + .value(secondaryISClientSecret)) + .addProperty(new org.wso2.identity.integration.test.rest.api.server.idp.v1.model.Property() + .key(IdentityConstants.Authenticator.OIDC.OAUTH2_AUTHZ_URL) + .value(SECONDARY_IS_AUTHORIZE_ENDPOINT)) + .addProperty(new org.wso2.identity.integration.test.rest.api.server.idp.v1.model.Property() + .key(IdentityConstants.Authenticator.OIDC.OAUTH2_TOKEN_URL) + .value(SECONDARY_IS_TOKEN_ENDPOINT)) + .addProperty(new org.wso2.identity.integration.test.rest.api.server.idp.v1.model.Property() + .key(IdentityConstants.Authenticator.OIDC.CALLBACK_URL) + .value(PRIMARY_IS_IDP_CALLBACK_URL)) + .addProperty(new org.wso2.identity.integration.test.rest.api.server.idp.v1.model.Property() + .key(IdentityConstants.Authenticator.OIDC.OIDC_LOGOUT_URL) + .value(SECONDARY_IS_LOGOUT_ENDPOINT)) + .addProperty(new org.wso2.identity.integration.test.rest.api.server.idp.v1.model.Property() + .key("commonAuthQueryParams") + .value("scope=" + OAuth2Constant.OAUTH2_SCOPE_OPENID_WITH_INTERNAL_LOGIN)); + + FederatedAuthenticatorRequest oidcAuthnConfig = new FederatedAuthenticatorRequest() + .defaultAuthenticatorId(ENCODED_PRIMARY_IS_IDP_AUTHENTICATOR_ID_OIDC) + .addAuthenticator(authenticator); + + ProvisioningRequest provision = new ProvisioningRequest() + .jit(new JustInTimeProvisioning() + .isEnabled(true) + .userstore("PRIMARY")); + + IdentityProviderPOSTRequest idpPostRequest = new IdentityProviderPOSTRequest() + .name(PRIMARY_IS_IDP_NAME) + .federatedAuthenticators(oidcAuthnConfig) + .provisioning(provision); + + primaryISIdpId = addIdentityProvider(PORT_OFFSET_0, idpPostRequest); + Assert.assertNotNull(primaryISIdpId, "Failed to create Identity Provider 'trustedIdP' in primary IS"); + } + + private OpenIDConnectConfiguration getAppOIDCConfigurations() { + + List grantTypes = new ArrayList<>(); + Collections.addAll(grantTypes, "authorization_code", "implicit", "password", "client_credentials", + "refresh_token", "urn:ietf:params:oauth:grant-type:saml2-bearer", "iwa:ntlm"); + + OpenIDConnectConfiguration oidcConfig = new OpenIDConnectConfiguration(); + oidcConfig.setGrantTypes(grantTypes); + oidcConfig.addCallbackURLsItem(PRIMARY_IS_IDP_CALLBACK_URL); + oidcConfig.setPublicClient(true); + return oidcConfig; + } + + private OpenIDConnectConfiguration getSP2OIDCConfigurations() { + + List grantTypes = new ArrayList<>(); + Collections.addAll(grantTypes, "authorization_code", "implicit", "password", "client_credentials", + "refresh_token", "urn:ietf:params:oauth:grant-type:saml2-bearer", "iwa:ntlm"); + + OpenIDConnectConfiguration oidcConfig = new OpenIDConnectConfiguration(); + oidcConfig.setGrantTypes(grantTypes); + oidcConfig.addCallbackURLsItem(PRIMARY_IS_IDP_CALLBACK_URL); + return oidcConfig; + } + + private HttpResponse sendLoginPost(HttpClient client, String sessionDataKey) throws IOException { + + List urlParameters = new ArrayList<>(); + urlParameters.add(new BasicNameValuePair("username", SECONDARY_IS_TEST_USERNAME)); + urlParameters.add(new BasicNameValuePair("password", SECONDARY_IS_TEST_PASSWORD)); + urlParameters.add(new BasicNameValuePair("sessionDataKey", sessionDataKey)); + log.info(">>> sendLoginPost:sessionDataKey: " + sessionDataKey); + + return sendPostRequestWithParameters(client, urlParameters, SECONDARY_IS_IDP_CALLBACK_URL); + } + + private HttpResponse sendPostRequestWithParameters(HttpClient client, List urlParameters, String url) + throws IOException { + + HttpPost request = new HttpPost(url); + request.setHeader("User-Agent", OAuth2Constant.USER_AGENT); + request.setEntity(new UrlEncodedFormEntity(urlParameters)); + + return client.execute(request); + } + + /** + * Builds a list of OAuth 2.0 parameters required for initiating the authorization process. + * The method constructs and returns a list of parameters necessary for initiating the OAuth 2.0 authorization process. + * + * @param consumerKey The client's unique identifier in the OAuth 2.0 system + * @return A list of NameValuePair representing the OAuth 2.0 parameters + */ + private List buildOAuth2Parameters(String consumerKey) { + + List urlParameters = new ArrayList<>(); + urlParameters.add( + new BasicNameValuePair(OAuth2Constant.OAUTH2_RESPONSE_TYPE, OAuth2Constant.AUTHORIZATION_CODE_NAME)); + urlParameters.add(new BasicNameValuePair(OAuth2Constant.OAUTH2_RESPONSE_MODE, RESPONSE_MODE)); + urlParameters.add(new BasicNameValuePair(OAuth2Constant.OAUTH2_CLIENT_ID, consumerKey)); + urlParameters.add(new BasicNameValuePair(OAuth2Constant.OAUTH2_REDIRECT_URI, PRIMARY_IS_IDP_CALLBACK_URL)); + urlParameters.add(new BasicNameValuePair(OAuth2Constant.OAUTH2_SCOPE, + OAuth2Constant.OAUTH2_SCOPE_OPENID_WITH_INTERNAL_LOGIN + " " + + OAuth2Constant.OAUTH2_SCOPE_EMAIL + " " + OAuth2Constant.OAUTH2_SCOPE_PROFILE)); + return urlParameters; + } + + /** + * Validates the structure and content of a Client Native Authentication JSON response. + * The method checks for the presence of required keys and their expected types in the provided JSON. + * It verifies the format of the authentication flow, authenticators, metadata, and required parameters. + * If the JSON response is not in the expected format, the method asserts failures using JUnit's Assert.fail(). + * + * @param json The JSON object representing the Client Native Authentication response + */ + private void validInitClientNativeAuthnResponse(JSONObject json) throws URISyntaxException { + + // Check for the presence of required keys and their expected types + if (json.containsKey(FLOW_ID) && json.containsKey(FLOW_STATUS) && json.containsKey(FLOW_TYPE) && + json.containsKey(NEXT_STEP) && json.containsKey(LINKS)) { + + flowId = (String) json.get(FLOW_ID); + flowStatus = (String) json.get(FLOW_STATUS); + + JSONObject nextStepNode = (JSONObject) json.get(NEXT_STEP); + if (nextStepNode.containsKey(STEP_TYPE) && nextStepNode.containsKey(AUTHENTICATORS)) { + + JSONArray authenticatorsArray = (JSONArray) nextStepNode.get(AUTHENTICATORS); + if (!authenticatorsArray.isEmpty()) { + + JSONObject authenticator = (JSONObject) authenticatorsArray.get(0); + + if (authenticator.containsKey(AUTHENTICATOR_ID) && authenticator.containsKey(AUTHENTICATOR) && + authenticator.containsKey(IDP) && authenticator.containsKey(METADATA) && + authenticator.containsKey(REQUIRED_PARAMS)) { + + authenticatorId = (String) authenticator.get(AUTHENTICATOR_ID); + if (!StringUtils.equals(authenticatorId, FEDERATE_AUTHENTICATOR_ID)) { + Assert.fail("Miss match of authenticator id. Expected : " + FEDERATE_AUTHENTICATOR_ID + + " but got : " + authenticatorId); + } + JSONObject metadataNode = (JSONObject) authenticator.get(METADATA); + if (metadataNode.containsKey(PROMPT_TYPE)) { + + JSONObject additionalData = (JSONObject) metadataNode.get(ADDITIONAL_DATA); + if (!additionalData.containsKey(REDIRECT_URL)) { + Assert.fail("Content of additional data for the authenticator is null in " + + "Client native authentication JSON Response."); + } + redirectURL = (String) additionalData.get(REDIRECT_URL); + if (StringUtils.isEmpty(redirectURL)) { + Assert.fail("Content of redirect url data for the authenticator is null in " + + "Client native authentication JSON Response."); + } + nonce = DataExtractUtil.getParamFromURIString(redirectURL, + "nonce"); + state = DataExtractUtil.getParamFromURIString(redirectURL, + "state"); + + } else { + Assert.fail("Params for the authenticator is null in " + + "Client native authentication JSON Response."); + } + } + } else { + Assert.fail("Authenticator is not expected format in Client native authentication"); + } + } else { + Assert.fail("Authenticators in Client native authentication JSON Response is null, " + + "expecting list of Authentication."); + } + JSONArray links = (JSONArray) json.get(LINKS); + JSONObject link = (JSONObject) links.get(0); + if (link.containsKey(HREF)) { + href = link.get(HREF).toString(); + } else { + Assert.fail("Link is not available for next step in Client native authentication JSON Response."); + } + } else { + Assert.fail("Client native authentication JSON Response is not in expected format."); + } + } + + private JSONObject getJsonObject(HttpResponse response) throws IOException, ParseException { + + String responseString = EntityUtils.toString(response.getEntity(), UTF_8); + EntityUtils.consume(response.getEntity()); + JSONParser parser = new JSONParser(); + return (JSONObject) parser.parse(responseString); + } + + private List getNameValuePairsForExternalFederation() { + + List urlParameters = new ArrayList<>(); + urlParameters.add( + new BasicNameValuePair(OAuth2Constant.OAUTH2_RESPONSE_TYPE, OAuth2Constant.AUTHORIZATION_CODE_NAME)); + urlParameters.add(new BasicNameValuePair(OAuth2Constant.OAUTH2_CLIENT_ID, secondaryISClientID)); + urlParameters.add(new BasicNameValuePair(OAuth2Constant.OAUTH2_REDIRECT_URI, PRIMARY_IS_IDP_CALLBACK_URL)); + urlParameters.add(new BasicNameValuePair(OAuth2Constant.OAUTH2_SCOPE, + OAuth2Constant.OAUTH2_SCOPE_OPENID_WITH_INTERNAL_LOGIN + " " + + OAuth2Constant.OAUTH2_SCOPE_EMAIL + " " + OAuth2Constant.OAUTH2_SCOPE_PROFILE)); + urlParameters.add(new BasicNameValuePair(OAuth2Constant.OAUTH2_NONCE, nonce)); + urlParameters.add(new BasicNameValuePair(STATE, state)); + return urlParameters; + } + + private void validateSecondaryISFederationResponse(HttpResponse response) throws IOException, URISyntaxException { + + String locationValue = getLocationHeaderValue(response); + EntityUtils.consume(response.getEntity()); + + Assert.assertTrue(locationValue.contains(OAuth2Constant.SESSION_DATA_KEY), + "sessionDataKey not found in response."); + String sessionDataKey = DataExtractUtil.getParamFromURIString(locationValue, OAuth2Constant.SESSION_DATA_KEY); + Assert.assertNotNull(sessionDataKey, "sessionDataKey is null."); + + response = sendLoginPost(client, sessionDataKey); + Assert.assertNotNull(response, "Login request failed. response is null."); + + locationValue = getLocationHeaderValue(response); + EntityUtils.consume(response.getEntity()); + sessionDataKey = DataExtractUtil.getParamFromURIString(locationValue, OAuth2Constant.SESSION_DATA_KEY); + + response = sendApprovalPost(client, sessionDataKey); + Assert.assertNotNull(response, "Approval request failed. response is invalid."); + + locationValue = getLocationHeaderValue(response); + + code = DataExtractUtil.getParamFromURIString(locationValue, OAuth2Constant.AUTHORIZATION_CODE_NAME); + state = DataExtractUtil.getParamFromURIString(locationValue, "state"); + + Assert.assertNotNull(code, "Authorization code is null or could not be found."); + EntityUtils.consume(response.getEntity()); + } + + private String generateAuthReqBody() { + + return "{\n" + + " \"flowId\": \"" + flowId + "\",\n" + + " \"selectedAuthenticator\": {\n" + + " \"authenticatorId\": \"" + authenticatorId + "\",\n" + + " \"params\": {\n" + + " \"code\": \"" + code + "\",\n" + + " \"state\": \"" + state + "\"\n" + + " }\n" + + " }\n" + + "}"; + } + + private void changeISConfiguration() throws AutomationUtilException, XPathExpressionException, IOException { + + String carbonHome = Utils.getResidentCarbonHome(); + File defaultTomlFile = getDeploymentTomlFile(carbonHome); + File emailOTPConfigFile = new File(getISResourceLocation() + File.separator + "jit" + File.separator + + "jit_user_association_config.toml"); + serverConfigurationManager = new ServerConfigurationManager(isServer); + serverConfigurationManager.applyConfigurationWithoutRestart(emailOTPConfigFile, defaultTomlFile, true); + serverConfigurationManager.restartGracefully(); + } + + private RequestedClaimConfiguration getRequestedClaim(String claimUri) { + + RequestedClaimConfiguration requestedClaim = new RequestedClaimConfiguration(); + requestedClaim.setClaim(new org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.Claim().uri(claimUri)); + return requestedClaim; + } +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oauth2/OAuth2AuthorizationCodeGrantJWTTokenTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oauth2/OAuth2AuthorizationCodeGrantJWTTokenTestCase.java old mode 100644 new mode 100755 index c7763ccf0d1..e22aeec2e1c --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oauth2/OAuth2AuthorizationCodeGrantJWTTokenTestCase.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oauth2/OAuth2AuthorizationCodeGrantJWTTokenTestCase.java @@ -67,6 +67,7 @@ import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import static org.wso2.identity.integration.test.utils.DataExtractUtil.KeyValue; import static org.wso2.identity.integration.test.utils.OAuth2Constant.ACCESS_TOKEN_ENDPOINT; diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oauth2/OAuth2IDTokenEncryptionTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oauth2/OAuth2IDTokenEncryptionTestCase.java index 5cd4f30e68e..68d0183d0b5 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oauth2/OAuth2IDTokenEncryptionTestCase.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oauth2/OAuth2IDTokenEncryptionTestCase.java @@ -57,21 +57,14 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.carbon.automation.engine.context.TestUserMode; -import org.wso2.carbon.automation.test.utils.common.TestConfigurationProvider; -import org.wso2.identity.integration.common.utils.ISIntegrationTest; import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.ApplicationResponseModel; import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.OpenIDConnectConfiguration; import org.wso2.identity.integration.test.utils.DataExtractUtil; import org.wso2.identity.integration.test.utils.OAuth2Constant; -import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.security.KeyStore; -import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.security.interfaces.RSAPrivateKey; import java.text.ParseException; @@ -84,10 +77,6 @@ */ public class OAuth2IDTokenEncryptionTestCase extends OAuth2ServiceAbstractIntegrationTest { - private RSAPrivateKey spPrivateKey; - - private X509Certificate spX509PublicCert; - private static final String CALLBACK_URL = "https://localhost/callback"; private static final String ENCRYPTION_ALGORITHM = "RSA-OAEP"; private static final String ENCRYPTION_METHOD = "A256GCM"; @@ -436,30 +425,6 @@ private String getLocationHeaderValue(HttpResponse response) { return location.getValue(); } - /** - * Initiate service provider keys required for the tests. - * - * @throws Exception If an error occurred while getting certificate. - */ - private void initServiceProviderKeys() throws Exception { - - KeyStore keyStore = KeyStore.getInstance(ISIntegrationTest.KEYSTORE_TYPE); - String pkcs12Path = TestConfigurationProvider.getResourceLocation("IS") + File.separator + "sp" + - File.separator + "keystores" + File.separator + "sp1KeyStore.p12"; - String pkcs12Password = "wso2carbon"; - - keyStore.load(Files.newInputStream(Paths.get(pkcs12Path)), pkcs12Password.toCharArray()); - - String alias = "wso2carbon"; - KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias, - new KeyStore.PasswordProtection(pkcs12Password.toCharArray())); - spPrivateKey = (RSAPrivateKey) pkEntry.getPrivateKey(); - - // Load certificate chain - Certificate[] chain = keyStore.getCertificateChain(alias); - spX509PublicCert = (X509Certificate) chain[0]; - } - /** * Sends a log in post to the IS instance and extract and return the sessionDataKeyConsent from the response. * diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oauth2/OAuth2RequestObjectSignatureValidationTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oauth2/OAuth2RequestObjectSignatureValidationTestCase.java index 9d6453fcddf..c0ff3b95329 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oauth2/OAuth2RequestObjectSignatureValidationTestCase.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oauth2/OAuth2RequestObjectSignatureValidationTestCase.java @@ -42,6 +42,7 @@ import org.testng.annotations.Test; import org.wso2.carbon.automation.engine.context.TestUserMode; import org.wso2.carbon.automation.test.utils.common.TestConfigurationProvider; +import org.wso2.carbon.utils.security.KeystoreUtils; import org.wso2.identity.integration.common.utils.ISIntegrationTest; import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.ApplicationResponseModel; import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.OpenIDConnectConfiguration; @@ -280,9 +281,10 @@ private String buildSignedJWT(String consumerKey, RSAPrivateKey privateKey) thro return signedJWT.serialize(); } - private void initServiceProviderKeys() throws Exception { + @Override + protected void initServiceProviderKeys() throws Exception { - KeyStore keyStore = KeyStore.getInstance(ISIntegrationTest.KEYSTORE_TYPE); + KeyStore keyStore = KeystoreUtils.getKeystoreInstance(ISIntegrationTest.KEYSTORE_TYPE); String pkcs12Path = TestConfigurationProvider.getResourceLocation("IS") + File.separator + "sp" + File.separator + "keystores" + File.separator + "sp1KeyStore.p12"; String pkcs12Password = "wso2carbon"; diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oauth2/OAuth2ServiceAbstractIntegrationTest.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oauth2/OAuth2ServiceAbstractIntegrationTest.java index d4a56857990..a5100fae8a4 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oauth2/OAuth2ServiceAbstractIntegrationTest.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oauth2/OAuth2ServiceAbstractIntegrationTest.java @@ -44,10 +44,12 @@ import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.wso2.carbon.automation.engine.context.TestUserMode; +import org.wso2.carbon.automation.test.utils.common.TestConfigurationProvider; import org.wso2.carbon.identity.application.common.model.xsd.Claim; import org.wso2.carbon.identity.application.common.model.xsd.Property; import org.wso2.carbon.identity.application.common.model.xsd.*; import org.wso2.carbon.identity.oauth.stub.dto.OAuthConsumerAppDTO; +import org.wso2.carbon.utils.security.KeystoreUtils; import org.wso2.identity.integration.common.clients.application.mgt.ApplicationManagementServiceClient; import org.wso2.identity.integration.common.clients.oauth.OauthAdminClient; import org.wso2.identity.integration.common.clients.usermgt.remote.RemoteUserStoreManagerServiceClient; @@ -78,11 +80,15 @@ import org.wso2.identity.integration.test.restclients.OAuth2RestClient; import org.wso2.identity.integration.test.util.Utils; import org.wso2.identity.integration.test.utils.OAuth2Constant; -import sun.security.provider.X509Factory; +import java.io.File; import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.security.KeyStore; import java.security.cert.CertificateEncodingException; import java.security.cert.X509Certificate; +import java.security.interfaces.RSAPrivateKey; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -109,6 +115,8 @@ public class OAuth2ServiceAbstractIntegrationTest extends ISIntegrationTest { private static final String customClaimURI2 = "http://wso2.org/claims/stateorprovince"; private static final String GRANT_TYPE_PASSWORD = "password"; private static final String SCOPE_PRODUCTION = "PRODUCTION"; + private static final String BEGIN_CERT = "-----BEGIN CERTIFICATE-----"; + private static final String END_CERT = "-----END CERTIFICATE-----"; public static final String OIDC = "oidc"; public static final String SAML = "saml"; private final static int TOMCAT_PORT = 8490; @@ -117,6 +125,8 @@ public class OAuth2ServiceAbstractIntegrationTest extends ISIntegrationTest { protected OauthAdminClient adminClient; protected RemoteUserStoreManagerServiceClient remoteUSMServiceClient; protected OAuth2RestClient restClient; + protected RSAPrivateKey spPrivateKey; + protected X509Certificate spX509PublicCert; /** @@ -177,6 +187,10 @@ public ApplicationResponseModel addApplication(ApplicationConfig applicationConf accessTokenConfiguration.type(applicationConfig.getTokenType().getTokenTypeProperty()); accessTokenConfiguration.applicationAccessTokenExpiryInSeconds(applicationConfig.getExpiryTime()); accessTokenConfiguration.userAccessTokenExpiryInSeconds(applicationConfig.getExpiryTime()); + // Add access token claim list. + List accessTokenClaimList = applicationConfig.getRequestedClaimList().stream() + .map(UserClaimConfig::getOidcClaimUri).collect(Collectors.toList()); + accessTokenConfiguration.accessTokenAttributes(accessTokenClaimList); oidcConfig.accessToken(accessTokenConfiguration); if (applicationConfig.getAudienceList() != null && !applicationConfig.getRequestedClaimList().isEmpty()) { @@ -903,10 +917,8 @@ public void updateApplicationCertificate(String appId, X509Certificate sp1X509Pu */ public String convertToPem(X509Certificate x509Certificate) throws CertificateEncodingException { - String certBegin = X509Factory.BEGIN_CERT; - String endCert = X509Factory.END_CERT; - String pemCert = new String(java.util.Base64.getEncoder().encode(x509Certificate.getEncoded())); - return certBegin + pemCert + endCert; + String pemCert = new String(java.util.Base64.getEncoder().encode(x509Certificate.getEncoded())); + return BEGIN_CERT + pemCert + END_CERT; } /** @@ -1273,4 +1285,23 @@ private ClaimConfiguration buildClaimConfigurationForRequestedClaims(List\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " " + SERVICE_PROVIDER_NAME + "\n" + - " \n" + - " \n" + - " \n" + - " token_validation\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " " + VALID_SCOPE + "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - ""; - private CloseableHttpClient client; - private EntitlementPolicyServiceClient entitlementPolicyClient; - private static boolean isLegacyRuntimeEnabled; - - @BeforeClass(alwaysRun = true) - public void testInit() throws Exception { - - super.init(TestUserMode.SUPER_TENANT_USER); - String carbonHome = Utils.getResidentCarbonHome(); - // Disabling dropping unregistered scopes to avoid scope validation failure. - File defaultTomlFile = getDeploymentTomlFile(carbonHome); - File configuredTomlFile = new File(getISResourceLocation() + File.separator - + "xacml_scope_validator.toml"); - - serverConfigurationManager = new ServerConfigurationManager(isServer); - serverConfigurationManager.applyConfigurationWithoutRestart(configuredTomlFile, defaultTomlFile, true); - serverConfigurationManager.restartGracefully(); - super.init(TestUserMode.SUPER_TENANT_USER); - isLegacyRuntimeEnabled = CarbonUtils.isLegacyAuthzRuntimeEnabled(); - entitlementPolicyClient = new EntitlementPolicyServiceClient(backendURL, sessionCookie); - } - - @AfterClass(alwaysRun = true) - public void atEnd() throws Exception { - - deleteApplication(); - removeOAuthApplicationData(); - serverConfigurationManager.restoreToLastConfiguration(false); - consumerKey = null; - consumerSecret = null; - entitlementPolicyClient.publishPolicies(new String[]{VALIDATE_SCOPE_BASED_POLICY_ID}, new String[]{"PDP " + - "Subscriber"}, "DELETE", true, null, 1); - entitlementPolicyClient.removePolicy(VALIDATE_SCOPE_BASED_POLICY_ID); - } - - @Test(groups = "wso2.is", description = "Check Oauth2 application registration.") - public void testRegisterApplication() throws Exception { - - OAuthConsumerAppDTO oAuthConsumerAppDTO = getBasicOAuthApp(CALLBACK_URL); - oAuthConsumerAppDTO.setScopeValidators(new String[]{SCOPE_VALIDATOR_NAME}); - ServiceProvider serviceProvider = registerServiceProviderWithOAuthInboundConfigs(oAuthConsumerAppDTO); - Assert.assertNotNull(serviceProvider, "OAuth App creation failed."); - Assert.assertNotNull(consumerKey, "Consumer Key is null."); - Assert.assertNotNull(consumerSecret, "Consumer Secret is null."); - String applicationId = serviceProvider.getApplicationResourceId(); - if (!isLegacyRuntimeEnabled) { - // Authorize few system APIs. - authorizeSystemAPIs(applicationId, - new ArrayList<>(Arrays.asList("/api/server/v1/tenants", "/scim2/Users", "/oauth2/introspect"))); - // Associate roles. - ApplicationPatchModel applicationPatch = new ApplicationPatchModel(); - AssociatedRolesConfig associatedRolesConfig = - new AssociatedRolesConfig().allowedAudience(AssociatedRolesConfig.AllowedAudienceEnum.ORGANIZATION); - applicationPatch = applicationPatch.associatedRoles(associatedRolesConfig); - updateApplication(applicationId, applicationPatch); - } - } - - @Test(groups = "wso2.is", description = "Check publishing a policy", dependsOnMethods = "testRegisterApplication") - public void testPublishPolicy() throws Exception { - - PolicyDTO policy = new PolicyDTO(); - policy.setPolicy(SCOPE_POLICY); - policy.setVersion("3.0"); - policy.setPolicy(policy.getPolicy().replaceAll(">\\s+<", "><").trim()); - policy.setPolicyId(VALIDATE_SCOPE_BASED_POLICY_ID); - entitlementPolicyClient.addPolicy(policy); - entitlementPolicyClient.publishPolicies(new String[]{VALIDATE_SCOPE_BASED_POLICY_ID}, new String[]{"PDP " + - "Subscriber"}, "CREATE", true, null, 1); - Assert.assertNotNull(entitlementPolicyClient.getPolicy(VALIDATE_SCOPE_BASED_POLICY_ID, true), "Entitlement " + - "service publish policy failed."); - } - - @Test(groups = "wso2.is", description = "Request access token with invalid token and validate it.", - dependsOnMethods = "testPublishPolicy") - public void testValidateTokenWithInValidScope() throws Exception { - - boolean result = getTokenAndValidate(new Scope(OAuth2Constant.OAUTH2_SCOPE_EMAIL)); - Assert.assertFalse(result, "Introspection is true."); - } - - @Test(groups = "wso2.is", description = "Request access token with valid token and validate it.", - dependsOnMethods = "testValidateTokenWithInValidScope") - public void testValidateTokenWithValidScope() throws Exception { - - boolean result; - if (isLegacyRuntimeEnabled) { - result = getTokenAndValidate(new Scope(VALID_SCOPE, INTROSPECT_SCOPE)); - } else { - result = getTokenAndValidate(new Scope(VALID_SCOPE, INTROSPECT_SCOPE_IN_NEW_AUTHZ_RUNTIME)); - } - Assert.assertTrue(result, "Introspection is false."); - } - - @Test(groups = "wso2.is", description = "Request access token with multiple token and validate it.", - dependsOnMethods = "testValidateTokenWithValidScope") - public void testValidateTokenWithMultipleScope() throws Exception { - - boolean result; - if (isLegacyRuntimeEnabled) { - result = getTokenAndValidate(new Scope(VALID_SCOPE, OAuth2Constant.OAUTH2_SCOPE_EMAIL, INTROSPECT_SCOPE)); - } else { - result = getTokenAndValidate(new Scope(VALID_SCOPE, OAuth2Constant.OAUTH2_SCOPE_EMAIL, - INTROSPECT_SCOPE_IN_NEW_AUTHZ_RUNTIME)); - } - Assert.assertTrue(result, "Introspection is false."); - } - - - /** - * Request access token with the scope and validate the token. - * - * @param scope scope - * @return whether validation success or not - * @throws Exception exception - */ - private boolean getTokenAndValidate(Scope scope) throws Exception { - - client = HttpClientBuilder.create().disableRedirectHandling().build(); - - try { - Secret password = new Secret(userInfo.getPassword()); - AuthorizationGrant passwordGrant = new ResourceOwnerPasswordCredentialsGrant( - userInfo.getUserNameWithoutDomain(), password); - ClientID clientID = new ClientID(consumerKey); - Secret clientSecret = new Secret(consumerSecret); - ClientAuthentication clientAuth = new ClientSecretBasic(clientID, clientSecret); - URI tokenEndpoint = new URI(getTenantQualifiedURL(OAuth2Constant.ACCESS_TOKEN_ENDPOINT, tenantInfo.getDomain())); - TokenRequest request = new TokenRequest(tokenEndpoint, clientAuth, passwordGrant, scope); - - HTTPResponse tokenHTTPResp = request.toHTTPRequest().send(); - Assert.assertNotNull(tokenHTTPResp, "Access token http response is null."); - AccessTokenResponse tokenResponse = AccessTokenResponse.parse(tokenHTTPResp); - Assert.assertNotNull(tokenResponse, "Access token response is null."); - - AccessToken accessToken = tokenResponse.getTokens().getAccessToken(); - URI introSpecEndpoint = new URI(OAuth2Constant.INTRO_SPEC_ENDPOINT); - BearerAccessToken bearerAccessToken = new BearerAccessToken(accessToken.getValue()); - TokenIntrospectionRequest TokenIntroRequest = new TokenIntrospectionRequest(introSpecEndpoint, - bearerAccessToken, - accessToken); - HTTPResponse introspectionHTTPResp = TokenIntroRequest.toHTTPRequest().send(); - Assert.assertNotNull(introspectionHTTPResp, "Introspection http response is null."); - - TokenIntrospectionResponse introspectionResponse = TokenIntrospectionResponse.parse(introspectionHTTPResp); - Assert.assertNotNull(introspectionResponse, "Introspection response is null."); - return introspectionResponse.indicatesSuccess(); - } finally { - client.close(); - } - } -} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oauth2/OIDCDiscoveryTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oauth2/OIDCDiscoveryTestCase.java index 84a178f8beb..36c65d828fa 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oauth2/OIDCDiscoveryTestCase.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oauth2/OIDCDiscoveryTestCase.java @@ -18,10 +18,19 @@ package org.wso2.identity.integration.test.oauth2; +import org.apache.commons.codec.binary.Base64; +import org.apache.http.HttpHeaders; import org.apache.http.HttpResponse; +import org.apache.http.client.config.CookieSpecs; +import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpGet; +import org.apache.http.config.Lookup; +import org.apache.http.config.RegistryBuilder; +import org.apache.http.cookie.CookieSpecProvider; import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; +import org.apache.http.impl.cookie.RFC6265CookieSpecProvider; import org.apache.wink.client.ClientConfig; import org.apache.wink.client.Resource; import org.apache.wink.client.RestClient; @@ -36,16 +45,19 @@ import org.testng.annotations.Test; import org.wso2.charon.core.schema.SCIMConstants; import org.wso2.identity.integration.common.utils.ISIntegrationTest; +import org.wso2.identity.integration.test.utils.OAuth2Constant; import java.io.IOException; import static org.testng.Assert.assertEquals; +import static org.wso2.identity.integration.test.utils.OAuth2Constant.USER_AGENT; public class OIDCDiscoveryTestCase extends ISIntegrationTest { public static final String WEBFINGER_ENDPOINT_SUFFIX = "/.well-known/webfinger"; public static final String RESOURCE = "resource"; public static final String REL = "rel"; + private CloseableHttpClient client; private String isServerBackendUrl; private static final String[] expectedResponseModes = {"fragment", "jwt", "fragment.jwt", "query", "form_post", @@ -64,11 +76,23 @@ public class OIDCDiscoveryTestCase extends ISIntegrationTest { public void testInit() throws Exception { super.init(); isServerBackendUrl = isServer.getContextUrls().getWebAppURLHttps(); + Lookup cookieSpecRegistry = RegistryBuilder.create() + .register(CookieSpecs.DEFAULT, new RFC6265CookieSpecProvider()) + .build(); + RequestConfig requestConfig = RequestConfig.custom() + .setCookieSpec(CookieSpecs.DEFAULT) + .build(); + client = HttpClientBuilder.create() + .disableRedirectHandling() + .setDefaultRequestConfig(requestConfig) + .setDefaultCookieSpecRegistry(cookieSpecRegistry) + .build(); } @AfterClass(alwaysRun = true) - public void atEnd() { + public void atEnd() throws Exception { + client.close(); } @Test(alwaysRun = true, groups = "wso2.is", description = "webfinger test", @@ -240,4 +264,80 @@ public void testDiscoveryForInvalidIssuer() throws IOException { "(HTTP 400) response"); } } + + @Test(dataProvider = "webFingerNegativeTestCases", alwaysRun = true, groups = "wso2.is", + dependsOnMethods = { "testDiscoveryForInvalidIssuer" }, description = "WebFinger negative test") + public void testWebFingerNegativeCases(String resource, String rel, int expectedStatusCode, String message) + throws Exception { + + String webFingerEndpoint = constructWebFingerEndpoint(resource, + (rel != null ? REL + "=" + rel : null)); + HttpResponse response = executeWebFingerRequest(webFingerEndpoint); + assertEquals(response.getStatusLine().getStatusCode(), expectedStatusCode, message); + } + + /** + * Data provider for WebFinger negative test cases. + */ + @DataProvider(name = "webFingerNegativeTestCases") + public Object[][] webFingerNegativeTestCases() { + return new Object[][]{ + {"acct:admin@localhost", null, 400, "Without REL URI, response should be BAD REQUEST."}, + {null, "http://openid.net/specs/connect/1.0/issuer", 400, + "Without resource, response should be BAD REQUEST."}, + {"", "http://openid.net/specs/connect/1.0/issuer", 404, + "Without resource, response should be NOT FOUND."}, + {"acct:admin", "http://openid.net/specs/connect/1.0/issuer", 400, + "Without proper resource, response should be BAD REQUEST."} + }; + } + + /** + * Utility method to construct the WebFinger endpoint. + */ + private String constructWebFingerEndpoint(String resource, + String relURI) { + + StringBuilder endpoint = new StringBuilder(isServerBackendUrl + + OIDCDiscoveryTestCase.WEBFINGER_ENDPOINT_SUFFIX + "?"); + if (resource != null) { + endpoint.append(OIDCDiscoveryTestCase.RESOURCE).append("=").append(resource); + } + if (relURI != null) { + endpoint.append("&"); + endpoint.append(relURI); + } + return endpoint.toString(); + } + + /** + * Utility method to execute a WebFinger request. + */ + private HttpResponse executeWebFingerRequest(String webFingerEndpoint) throws Exception { + + ClientConfig clientConfig = new ClientConfig(); + BasicAuthSecurityHandler basicAuth = new BasicAuthSecurityHandler(); + basicAuth.setUserName(userInfo.getUserName()); + basicAuth.setPassword(userInfo.getPassword()); + clientConfig.handlers(basicAuth); + + HttpGet request = new HttpGet(webFingerEndpoint); + request.addHeader(HttpHeaders.AUTHORIZATION, OAuth2Constant.BASIC_HEADER + " " + + getBase64EncodedString(userInfo.getUserName(), userInfo.getPassword())); + request.addHeader("User-Agent", USER_AGENT); + + return client.execute(request); + } + + /** + * Get base64 encoded string of username and password. + * + * @param username Username of Admin. + * @param password Password of Admin. + * @return Base 64 encoded string. + */ + private String getBase64EncodedString(String username, String password) { + + return new String(Base64.encodeBase64((username + ":" + password).getBytes())); + } } diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oauth2/consented/token/OAuth2ServiceAuthCodeGrantJWTAccessTokenWithConsentedTokenColumnTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oauth2/consented/token/OAuth2ServiceAuthCodeGrantJWTAccessTokenWithConsentedTokenColumnTestCase.java index 3716f8ec2bc..1327c122039 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oauth2/consented/token/OAuth2ServiceAuthCodeGrantJWTAccessTokenWithConsentedTokenColumnTestCase.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oauth2/consented/token/OAuth2ServiceAuthCodeGrantJWTAccessTokenWithConsentedTokenColumnTestCase.java @@ -239,13 +239,14 @@ private void validateUserClaims(OIDCTokens oidcTokens) throws JSONException, Par accessToken = oidcTokens.getAccessToken().getValue(); refreshToken = oidcTokens.getRefreshToken().getValue(); - // Get the user info from the JWT access token. + // Check if user claims are present in access token. JSONObject jwtJsonObject = new JSONObject(new String(Base64.decodeBase64(accessToken.split("\\.")[1]))); - String email = jwtJsonObject.getString(EMAIL_OIDC_CLAIM); - Assert.assertEquals(USER_EMAIL, email, "Requested user claim (Email) is not present in the JWT access " - + "token."); - Assert.assertTrue(jwtJsonObject.isNull(ADDRESS_OIDC_CLAIM), "Non-consented user claim (address) is" - + " present in the JWT access token."); + try { + Object emailClaim = jwtJsonObject.get(EMAIL_OIDC_CLAIM); + Assert.fail("Requested user claim (email) is present in the JWT access token."); + } catch (JSONException e) { + Assert.assertTrue(true, "Requested user claim (email) is present in the JWT access token."); + } // Get the user info from the ID token. Assert.assertEquals(oidcTokens.getIDToken().getJWTClaimsSet().getClaim(EMAIL_OIDC_CLAIM).toString(), USER_EMAIL, diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oauth2/consented/token/OAuth2ServicePasswordGrantJWTAccessTokenWithConsentedTokenColumnTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oauth2/consented/token/OAuth2ServicePasswordGrantJWTAccessTokenWithConsentedTokenColumnTestCase.java index 4cd2a23c29d..571ed18d46f 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oauth2/consented/token/OAuth2ServicePasswordGrantJWTAccessTokenWithConsentedTokenColumnTestCase.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oauth2/consented/token/OAuth2ServicePasswordGrantJWTAccessTokenWithConsentedTokenColumnTestCase.java @@ -77,7 +77,6 @@ public void testRegisterApplication() throws Exception { registerApplication(); } - @Test(description = "This test case tests the JWT access token generation using password grant type.", dependsOnMethods = "testRegisterApplication") public void testPasswordGrantBasedAccessTokenGeneration() throws IOException, URISyntaxException, ParseException, @@ -139,13 +138,14 @@ private void validateUserClaims(OIDCTokens oidcTokens) throws JSONException, jav // Get the user info from the JWT access token. JSONObject jwtJsonObject = new JSONObject(new String(Base64.decodeBase64(accessToken.split( "\\.")[1]))); - String email = jwtJsonObject.get(EMAIL_OIDC_CLAIM).toString(); - String country = ((JSONObject) jwtJsonObject.get(ADDRESS_OIDC_CLAIM)).get(COUNTRY_OIDC_CLAIM).toString(); - // Check the user info of the JWT access token. - Assert.assertEquals(USER_EMAIL, email, "Requested user claim (email) is not present in the JWT access token."); - Assert.assertEquals(COUNTRY, country, "Requested user claim (country) is not present in the JWT " - + "access token."); + // Check if user claims are present in access token. + try { + Object emailClaim = jwtJsonObject.get(EMAIL_OIDC_CLAIM); + Assert.fail("Requested user claim (email) is present in the JWT access token."); + } catch (JSONException e) { + Assert.assertTrue(true, "Requested user claim (email) is present in the JWT access token."); + } Assert.assertEquals(oidcTokens.getIDToken().getJWTClaimsSet().getClaim(EMAIL_OIDC_CLAIM), USER_EMAIL, "Requested user claims is not returned back with the ID token."); diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oidc/OIDCAbstractIntegrationTest.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oidc/OIDCAbstractIntegrationTest.java index d026577b135..1f5dc59d813 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oidc/OIDCAbstractIntegrationTest.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oidc/OIDCAbstractIntegrationTest.java @@ -20,13 +20,11 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.CookieStore; import org.apache.http.client.HttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.util.EntityUtils; +import org.apache.http.message.BasicNameValuePair; import org.testng.Assert; import org.wso2.carbon.automation.engine.context.TestUserMode; import org.wso2.identity.integration.test.oauth2.OAuth2ServiceAbstractIntegrationTest; @@ -53,6 +51,8 @@ import java.util.List; import java.util.Map; +import static org.wso2.identity.integration.test.utils.OAuth2Constant.AUTHORIZE_ENDPOINT_URL; + /** * This class defines basic functionality needed to initiate an OIDC test. */ @@ -127,7 +127,7 @@ public void createApplication(OIDCApplication application) throws Exception { createApplication(applicationModel, application); } - private void createApplication(ApplicationModel applicationModel, OIDCApplication application) throws Exception { + public void createApplication(ApplicationModel applicationModel, OIDCApplication application) throws Exception { log.info("Creating application " + application.getApplicationName()); @@ -188,28 +188,19 @@ public void testSendAuthenticationRequest(OIDCApplication application, boolean i HttpClient client, CookieStore cookieStore) throws Exception { - List urlParameters = OIDCUtilTest.getNameValuePairs(application, - getTenantQualifiedURL(OAuth2Constant.APPROVAL_URL, tenantInfo.getDomain())); - - HttpResponse response = sendPostRequestWithParameters(client, urlParameters, String.format - (OIDCUtilTest.targetApplicationUrl, application.getApplicationContext() + OAuth2Constant.PlaygroundAppPaths - .appUserAuthorizePath)); + List urlParameters = new ArrayList<>(); + urlParameters.add(new BasicNameValuePair("response_type", OAuth2Constant.OAUTH2_GRANT_TYPE_CODE)); + urlParameters.add(new BasicNameValuePair("client_id", application.getClientId())); + urlParameters.add(new BasicNameValuePair("redirect_uri", application.getCallBackURL())); - Header locationHeader = response.getFirstHeader(OAuth2Constant.HTTP_RESPONSE_HEADER_LOCATION); - EntityUtils.consume(response.getEntity()); + urlParameters.add(new BasicNameValuePair("scope", "openid")); - if (isFirstAuthenticationRequest) { - response = sendGetRequest(client, locationHeader.getValue()); - } else { - HttpClient httpClientWithoutAutoRedirections = HttpClientBuilder.create().disableRedirectHandling() - .setDefaultCookieStore(cookieStore).build(); - response = sendGetRequest(httpClientWithoutAutoRedirections, locationHeader.getValue()); - } + HttpResponse response = sendPostRequestWithParameters(client, urlParameters, + getTenantQualifiedURL(AUTHORIZE_ENDPOINT_URL, tenantInfo.getDomain())); Map keyPositionMap = new HashMap<>(1); if (isFirstAuthenticationRequest) { OIDCUtilTest.setSessionDataKey(response, keyPositionMap); - } else { Assert.assertFalse(Utils.requestMissingClaims(response)); } diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oidc/OIDCAccessTokenAttributesTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oidc/OIDCAccessTokenAttributesTestCase.java new file mode 100755 index 00000000000..c760ba0953f --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oidc/OIDCAccessTokenAttributesTestCase.java @@ -0,0 +1,268 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.identity.integration.test.oidc; + +import com.nimbusds.jwt.JWTClaimsSet; +import com.nimbusds.jwt.SignedJWT; +import io.restassured.RestAssured; +import io.restassured.response.Response; +import org.apache.http.HttpStatus; +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.identity.integration.test.oidc.bean.OIDCApplication; +import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.AccessTokenConfiguration; +import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.ApplicationModel; +import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.InboundProtocols; +import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.OpenIDConnectConfiguration; +import org.wso2.identity.integration.test.utils.OAuth2Constant; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.CoreMatchers.notNullValue; + +public class OIDCAccessTokenAttributesTestCase extends OIDCAbstractIntegrationTest { + + private static final String OAUTH2_TOKEN_ENDPOINT_URI = "/oauth2/token"; + private static final String SERVICES = "/services"; + private OIDCApplication application; + private OpenIDConnectConfiguration oidcInboundConfig; + protected String refreshToken; + protected String sessionDataKey; + + @BeforeClass(alwaysRun = true) + public void testInit() throws Exception { + + super.init(); + + RestAssured.baseURI = backendURL.replace(SERVICES, ""); + + // Create a user + OIDCUtilTest.initUser(); + createUser(OIDCUtilTest.user); + + // Create application + OIDCUtilTest.initApplications(); + application = OIDCUtilTest.applications.get(OIDCUtilTest.playgroundAppTwoAppName); + createApplication(application); + } + + @AfterClass(alwaysRun = true) + public void testClear() throws Exception { + + deleteUser(OIDCUtilTest.user); + deleteApplication(application); + clear(); + } + + @Test(groups = "wso2.is", description = "Validate access token attributes with password grant") + public void testValidateAccessTokenAttributesWithPasswordGrant() throws Exception { + + Map params = new HashMap<>(); + params.put("grant_type", OAuth2Constant.OAUTH2_GRANT_TYPE_RESOURCE_OWNER); + params.put("scope", ""); + params.put("username", OIDCUtilTest.user.getUserName()); + params.put("password", OIDCUtilTest.user.getPassword()); + + Response response = getResponseOfFormPostWithAuth(OAUTH2_TOKEN_ENDPOINT_URI, params, new HashMap<>(), + application.getClientId(), application.getClientSecret()); + + response.then() + .log().ifValidationFails() + .assertThat() + .statusCode(HttpStatus.SC_OK) + .body("access_token", notNullValue()) + .body("refresh_token", notNullValue()); + + String accessToken = response.then().extract().path("access_token"); + refreshToken = response.then().extract().path("refresh_token"); + Assert.assertNotNull(accessToken, "Access token is null"); + JWTClaimsSet jwtClaimsSet = SignedJWT.parse(accessToken).getJWTClaimsSet(); + Assert.assertNotNull(jwtClaimsSet.getClaim("username"), "Username is null."); + + } + + @Test(groups = "wso2.is", description = "Validate access token attributes with refresh grant", + dependsOnMethods = "testValidateAccessTokenAttributesWithPasswordGrant") + public void testValidateAccessTokenAttributesWithRefreshGrant() throws Exception { + + Map params = new HashMap<>(); + params.put("grant_type", OAuth2Constant.OAUTH2_GRANT_TYPE_REFRESH_TOKEN); + params.put(OAuth2Constant.OAUTH2_GRANT_TYPE_REFRESH_TOKEN, refreshToken); + + Response response = getResponseOfFormPostWithAuth(OAUTH2_TOKEN_ENDPOINT_URI, params, new HashMap<>(), + application.getClientId(), application.getClientSecret()); + + response.then() + .log().ifValidationFails() + .assertThat() + .statusCode(HttpStatus.SC_OK) + .body("access_token", notNullValue()) + .body("refresh_token", notNullValue()); + + String accessToken = response.then().extract().path("access_token"); + refreshToken = response.then().extract().path("refresh_token"); + Assert.assertNotNull(accessToken, "Access token is null"); + JWTClaimsSet jwtClaimsSet = SignedJWT.parse(accessToken).getJWTClaimsSet(); + Assert.assertNotNull(jwtClaimsSet.getClaim("username"), "Username is null."); + } + + @Test(groups = "wso2.is", description = "Update access token attributes of the application", + dependsOnMethods = "testValidateAccessTokenAttributesWithRefreshGrant") + public void testUpdateAccessTokenAttributes() throws Exception { + + AccessTokenConfiguration accessTokenConfig = new AccessTokenConfiguration().type("JWT"); + accessTokenConfig.setUserAccessTokenExpiryInSeconds(3600L); + accessTokenConfig.setApplicationAccessTokenExpiryInSeconds(3600L); + // Add access token attributes + List accessTokenAttributes = new ArrayList<>(); + accessTokenAttributes.add("username"); + accessTokenConfig.setAccessTokenAttributes(accessTokenAttributes); + oidcInboundConfig.setAccessToken(accessTokenConfig); + updateApplicationInboundConfig(application.getApplicationId(), oidcInboundConfig, OIDC); + + OpenIDConnectConfiguration updatedOidcInboundConfig = + getOIDCInboundDetailsOfApplication(application.getApplicationId()); + Assert.assertEquals(updatedOidcInboundConfig.getAccessToken().getAccessTokenAttributes().size(),1, + "Access token attribute should not be empty."); + } + + @Test(groups = "wso2.is", description = "Validate access token attributes for empty allowed attributes", + dependsOnMethods = "testUpdateAccessTokenAttributes") + public void testValidateAccessTokenAttributesForEmptyAllowedAttributes() throws Exception { + + Map params = new HashMap<>(); + params.put("grant_type", OAuth2Constant.OAUTH2_GRANT_TYPE_RESOURCE_OWNER); + params.put("scope", ""); + params.put("username", OIDCUtilTest.user.getUserName()); + params.put("password", OIDCUtilTest.user.getPassword()); + + Response response = getResponseOfFormPostWithAuth(OAUTH2_TOKEN_ENDPOINT_URI, params, new HashMap<>(), + application.getClientId(), application.getClientSecret()); + + response.then() + .log().ifValidationFails() + .assertThat() + .statusCode(HttpStatus.SC_OK) + .body("access_token", notNullValue()) + .body("refresh_token", notNullValue()); + + String accessToken = response.then().extract().path("access_token"); + refreshToken = response.then().extract().path("refresh_token"); + Assert.assertNotNull(accessToken, "Access token is null"); + JWTClaimsSet jwtClaimsSet = SignedJWT.parse(accessToken).getJWTClaimsSet(); + Assert.assertNotNull(jwtClaimsSet.getClaim("username"), "Username is null."); + } + + @Test(groups = "wso2.is", description = "Validate access token attributes for empty allowed attributes with " + + "refresh grant", dependsOnMethods = "testValidateAccessTokenAttributesForEmptyAllowedAttributes") + public void testValidateAccessTokenAttributesForEmptyAllowedAttributesWithRefreshGrant() throws Exception { + + Map params = new HashMap<>(); + params.put("grant_type", OAuth2Constant.OAUTH2_GRANT_TYPE_REFRESH_TOKEN); + params.put(OAuth2Constant.OAUTH2_GRANT_TYPE_REFRESH_TOKEN, refreshToken); + + Response response = getResponseOfFormPostWithAuth(OAUTH2_TOKEN_ENDPOINT_URI, params, new HashMap<>(), + application.getClientId(), application.getClientSecret()); + + response.then() + .log().ifValidationFails() + .assertThat() + .statusCode(HttpStatus.SC_OK) + .body("access_token", notNullValue()) + .body("refresh_token", notNullValue()); + + String accessToken = response.then().extract().path("access_token"); + refreshToken = response.then().extract().path("refresh_token"); + Assert.assertNotNull(accessToken, "Access token is null"); + JWTClaimsSet jwtClaimsSet = SignedJWT.parse(accessToken).getJWTClaimsSet(); + Assert.assertNotNull(jwtClaimsSet.getClaim("username"), "Username is null."); + } + + /** + * Invoke given endpointUri for Form POST request with given body, headers and Basic authentication credentials. + * + * @param endpointUri endpoint to be invoked. + * @param params map of parameters to be added to the request. + * @param headers map of headers to be added to the request. + * @param username basic auth username. + * @param password basic auth password. + * @return response. + */ + protected Response getResponseOfFormPostWithAuth(String endpointUri, Map params, Map + headers, String username, String password) { + + return given().auth().preemptive().basic(username, password) + .headers(headers) + .params(params) + .when() + .post(endpointUri); + } + + /** + * Create an OIDC application. + * + * @param application application instance. + * @throws Exception If an error creating an application. + */ + public void createApplication(OIDCApplication application) throws Exception { + + ApplicationModel applicationModel = new ApplicationModel(); + createAccessTokenAttributesEnabledApplication(applicationModel, application); + } + + private void createAccessTokenAttributesEnabledApplication(ApplicationModel applicationModel, + OIDCApplication application) throws Exception { + + List grantTypes = new ArrayList<>(); + Collections.addAll(grantTypes, OAuth2Constant.OAUTH2_GRANT_TYPE_RESOURCE_OWNER, + OAuth2Constant.OAUTH2_GRANT_TYPE_REFRESH_TOKEN); + + OpenIDConnectConfiguration oidcConfig = new OpenIDConnectConfiguration(); + oidcConfig.setGrantTypes(grantTypes); + oidcConfig.addCallbackURLsItem(application.getCallBackURL()); + + AccessTokenConfiguration accessTokenConfig = new AccessTokenConfiguration().type("JWT"); + accessTokenConfig.setUserAccessTokenExpiryInSeconds(3600L); + accessTokenConfig.setApplicationAccessTokenExpiryInSeconds(3600L); + // Add access token attributes + List accessTokenAttributes = new ArrayList<>(); + Collections.addAll(accessTokenAttributes, "username", "email"); + accessTokenConfig.setAccessTokenAttributes(accessTokenAttributes); + + oidcConfig.setAccessToken(accessTokenConfig); + + applicationModel.setName(application.getApplicationName()); + applicationModel.setInboundProtocolConfiguration(new InboundProtocols().oidc(oidcConfig)); + + String applicationId = addApplication(applicationModel); + oidcConfig = getOIDCInboundDetailsOfApplication(applicationId); + oidcInboundConfig = oidcConfig; + + application.setApplicationId(applicationId); + application.setClientId(oidcConfig.getClientId()); + application.setClientSecret(oidcConfig.getClientSecret()); + } +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oidc/OIDCAuthCodeGrantSSOTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oidc/OIDCAuthCodeGrantSSOTestCase.java index 730c5aed824..221ebf6e788 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oidc/OIDCAuthCodeGrantSSOTestCase.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oidc/OIDCAuthCodeGrantSSOTestCase.java @@ -33,6 +33,7 @@ import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.cookie.RFC6265CookieSpecProvider; +import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.json.simple.JSONValue; @@ -40,6 +41,7 @@ import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; +import org.wso2.identity.integration.test.base.MockApplicationServer; import org.wso2.identity.integration.test.oidc.bean.OIDCApplication; import org.wso2.identity.integration.test.rest.api.user.common.model.Email; import org.wso2.identity.integration.test.rest.api.user.common.model.Name; @@ -49,7 +51,6 @@ import org.wso2.identity.integration.test.utils.OAuth2Constant; import java.io.BufferedReader; -import java.io.IOException; import java.io.InputStreamReader; import java.net.URI; import java.util.ArrayList; @@ -57,6 +58,11 @@ import java.util.List; import java.util.Map; +import static org.wso2.identity.integration.test.utils.OAuth2Constant.ACCESS_TOKEN_ENDPOINT; +import static org.wso2.identity.integration.test.utils.OAuth2Constant.AUTHORIZATION_HEADER; +import static org.wso2.identity.integration.test.utils.OAuth2Constant.AUTHORIZE_ENDPOINT_URL; +import static org.wso2.identity.integration.test.utils.OAuth2Constant.OAUTH2_GRANT_TYPE_AUTHORIZATION_CODE; + /** * This test class tests OIDC SSO functionality for two replying party applications. */ @@ -76,6 +82,7 @@ public class OIDCAuthCodeGrantSSOTestCase extends OIDCAbstractIntegrationTest { protected RequestConfig requestConfig; protected HttpClient client; protected List consentParameters = new ArrayList<>(); + private MockApplicationServer mockApplicationServer; @BeforeClass(alwaysRun = true) public void testInit() throws Exception { @@ -100,6 +107,9 @@ public void testInit() throws Exception { .setDefaultCookieStore(cookieStore) .build(); + mockApplicationServer = new MockApplicationServer(); + mockApplicationServer.start(); + } @AfterClass(alwaysRun = true) @@ -108,6 +118,7 @@ public void testClear() throws Exception { deleteUser(user); deleteApplications(); clear(); + mockApplicationServer.stop(); } @Test(groups = "wso2.is", description = "Test authz endpoint before creating a valid session") @@ -122,12 +133,13 @@ public void testAuthzRequestWithoutValidSessionForIDENTITY5581() throws Exceptio .addParameter("prompt", "none") .addParameter("redirect_uri", application.getCallBackURL()).build(); HttpResponse httpResponse = sendGetRequest(client, uri.toString()); - String contentData = DataExtractUtil.getContentData(httpResponse); - Assert.assertTrue(contentData.contains("login_required")); + EntityUtils.consume(httpResponse.getEntity()); + Assert.assertTrue(mockApplicationServer.getErrorCode(application.getApplicationName()).contains("login_required")); } - @Test(groups = "wso2.is", description = "Initiate authentication request from playground.appone", dependsOnMethods = "testAuthzRequestWithoutValidSessionForIDENTITY5581") + @Test(groups = "wso2.is", description = "Initiate authentication request from playground.appone", + dependsOnMethods = "testAuthzRequestWithoutValidSessionForIDENTITY5581") public void testSendAuthenticationRequestFromRP1() throws Exception { testSendAuthenticationRequest(applications.get(OIDCUtilTest.playgroundAppOneAppName), true, client, cookieStore); @@ -164,7 +176,8 @@ public void testUserClaimsFromRP1() throws Exception { @Test(groups = "wso2.is", description = "Initiate authentication request from playground.apptwo") public void testSendAuthenticationRequestFromRP2() throws Exception { - testSendAuthenticationRequest(applications.get(OIDCUtilTest.playgroundAppTwoAppName), false, client, cookieStore); + testSendAuthenticationRequest(applications.get(OIDCUtilTest.playgroundAppTwoAppName), false, client, + cookieStore); } @Test(groups = "wso2.is", description = "Approve consent for playground.apptwo", dependsOnMethods = @@ -189,23 +202,22 @@ public void testUserClaimsFromRP2() throws Exception { } public void testSendAuthenticationRequest(OIDCApplication application, boolean isFirstAuthenticationRequest, - HttpClient client, CookieStore cookieStore) - throws Exception { - - List urlParameters = OIDCUtilTest.getNameValuePairs(application); - HttpResponse response = sendPostRequestWithParameters(client, urlParameters, String.format - (OIDCUtilTest.targetApplicationUrl, application.getApplicationContext() + OAuth2Constant.PlaygroundAppPaths - .appUserAuthorizePath)); - Assert.assertNotNull(response, "Authorization request failed for " + application.getApplicationName() + ". " - + "Authorized response is null"); + HttpClient client, CookieStore cookieStore) throws Exception { - Header locationHeader = response.getFirstHeader(OAuth2Constant.HTTP_RESPONSE_HEADER_LOCATION); + List urlParameters = new ArrayList<>(); + urlParameters.add(new BasicNameValuePair("response_type", OAuth2Constant.OAUTH2_GRANT_TYPE_CODE)); + urlParameters.add(new BasicNameValuePair("client_id", application.getClientId())); + urlParameters.add(new BasicNameValuePair("redirect_uri", application.getCallBackURL())); - Assert.assertNotNull(locationHeader, "Authorization request failed for " + application.getApplicationName() + - ". Authorized response header is null"); - EntityUtils.consume(response.getEntity()); + urlParameters.add(new BasicNameValuePair("scope", "openid email profile")); + HttpResponse response; if (isFirstAuthenticationRequest) { + response = sendPostRequestWithParameters(client, urlParameters, + getTenantQualifiedURL(AUTHORIZE_ENDPOINT_URL, tenantInfo.getDomain())); + Header locationHeader = response.getFirstHeader(OAuth2Constant.HTTP_RESPONSE_HEADER_LOCATION); + EntityUtils.consume(response.getEntity()); + response = sendGetRequest(client, locationHeader.getValue()); } else { HttpClient httpClientWithoutAutoRedirections = HttpClientBuilder.create() @@ -213,11 +225,12 @@ public void testSendAuthenticationRequest(OIDCApplication application, boolean i .setDefaultRequestConfig(requestConfig) .disableRedirectHandling() .setDefaultCookieStore(cookieStore).build(); - response = sendGetRequest(httpClientWithoutAutoRedirections, locationHeader.getValue()); + response = sendPostRequestWithParameters(httpClientWithoutAutoRedirections, urlParameters, + getTenantQualifiedURL(AUTHORIZE_ENDPOINT_URL, tenantInfo.getDomain())); } - Assert.assertNotNull(response, "Authorization request failed for " + application.getApplicationName() + ". " - + "Authorized user response is null."); + Assert.assertNotNull(response, "Authorization request failed for " + application.getApplicationName() + + ". Authorized user response is null."); Map keyPositionMap = new HashMap<>(1); if (isFirstAuthenticationRequest) { @@ -238,12 +251,11 @@ public void testSendAuthenticationRequest(OIDCApplication application, boolean i String pastrCookie = Utils.getPastreCookie(response); Assert.assertNotNull(pastrCookie, "pastr cookie not found in response."); EntityUtils.consume(response.getEntity()); - Header oauthConsentLocationHeader = consentLocationHeader; - Assert.assertNotNull(oauthConsentLocationHeader, "OAuth consent url is null for " + - oauthConsentLocationHeader.getValue()); + Assert.assertNotNull(consentLocationHeader, "OAuth consent url is null for " + + consentLocationHeader.getValue()); consentParameters.addAll(Utils.getConsentRequiredClaimsFromResponse(response)); - response = sendGetRequest(client, oauthConsentLocationHeader.getValue()); + response = sendGetRequest(client, consentLocationHeader.getValue()); keyPositionMap.put("name=\"sessionDataKeyConsent\"", 1); List keyValues = DataExtractUtil.extractSessionConsentDataFromResponse @@ -272,6 +284,7 @@ private void testAuthentication(OIDCApplication application) throws Exception { EntityUtils.consume(response.getEntity()); response = sendGetRequest(client, locationHeader.getValue()); + Map keyPositionMap = new HashMap<>(1); keyPositionMap.put("name=\"sessionDataKeyConsent\"", 1); List keyValues = DataExtractUtil.extractSessionConsentDataFromResponse(response, @@ -297,16 +310,10 @@ private void testConsentApproval(OIDCApplication application) throws Exception { EntityUtils.consume(response.getEntity()); response = sendPostRequest(client, locationHeader.getValue()); - Assert.assertNotNull(response, "Authorization code response is invalid for " + application.getApplicationName - ()); - - Map keyPositionMap = new HashMap<>(1); - keyPositionMap.put("Authorization Code", 1); - List keyValues = DataExtractUtil.extractTableRowDataFromResponse(response, - keyPositionMap); - Assert.assertNotNull(keyValues, "Authorization code not received for " + application.getApplicationName()); + Assert.assertNotNull(response, "Authorization code response is invalid for " + + application.getApplicationName()); - authorizationCode = keyValues.get(0).getValue(); + authorizationCode = mockApplicationServer.getAuthorizationCodeForApp(application.getApplicationName()); Assert.assertNotNull(authorizationCode, "Authorization code not received for " + application .getApplicationName()); EntityUtils.consume(response.getEntity()); @@ -314,35 +321,33 @@ private void testConsentApproval(OIDCApplication application) throws Exception { private void testGetAccessToken(OIDCApplication application) throws Exception { - HttpResponse response = sendGetAccessTokenPost(client, application); - Assert.assertNotNull(response, "Access token response is invalid for " + application.getApplicationName()); - EntityUtils.consume(response.getEntity()); - - response = sendPostRequest(client, String.format(OIDCUtilTest.targetApplicationUrl, application.getApplicationContext() + - OAuth2Constant.PlaygroundAppPaths.appAuthorizePath)); - - Map keyPositionMap = new HashMap<>(1); - keyPositionMap.put("name=\"accessToken\"", 1); - List keyValues = DataExtractUtil.extractInputValueFromResponse(response, - keyPositionMap); - Assert.assertNotNull(keyValues, "Access token not received for " + application.getApplicationName()); - - accessToken = keyValues.get(0).getValue(); - Assert.assertNotNull(accessToken, "Access token not received for " + application.getApplicationName()); - EntityUtils.consume(response.getEntity()); - - response = sendPostRequest(client, String.format(OIDCUtilTest.targetApplicationUrl, application.getApplicationContext() + - OAuth2Constant.PlaygroundAppPaths.appAuthorizePath)); - - keyPositionMap = new HashMap<>(1); - keyPositionMap.put("id=\"loggedUser\"", 1); - keyValues = DataExtractUtil.extractLabelValueFromResponse(response, keyPositionMap); - Assert.assertNotNull(keyValues, "No user logged in for " + application.getApplicationName()); + List urlParameters = new ArrayList<>(); + urlParameters.add(new BasicNameValuePair("code", authorizationCode)); + urlParameters.add(new BasicNameValuePair("grant_type", OAUTH2_GRANT_TYPE_AUTHORIZATION_CODE)); + urlParameters.add(new BasicNameValuePair("redirect_uri", application.getCallBackURL())); + urlParameters.add(new BasicNameValuePair("client_id", application.getClientSecret())); + + urlParameters.add(new BasicNameValuePair("scope", "openid")); + + List
headers = new ArrayList<>(); + headers.add(new BasicHeader(AUTHORIZATION_HEADER, + OAuth2Constant.BASIC_HEADER + " " + getBase64EncodedString(application.getClientId(), + application.getClientSecret()))); + headers.add(new BasicHeader("Content-Type", "application/x-www-form-urlencoded")); + headers.add(new BasicHeader("User-Agent", OAuth2Constant.USER_AGENT)); + + HttpResponse response = sendPostRequest(client, headers, urlParameters, + getTenantQualifiedURL(ACCESS_TOKEN_ENDPOINT, tenantInfo.getDomain())); + String responseString = EntityUtils.toString(response.getEntity()); + Map responseMap = (Map) JSONValue.parse(responseString); + accessToken = (String) responseMap.get("access_token"); + + String idToken = (String) responseMap.get("id_token"); + String[] tokenParts = idToken.split("\\."); + String payload = new String(java.util.Base64.getUrlDecoder().decode(tokenParts[1])); + Map parsedIdToken = (Map) JSONValue.parse(payload); + Assert.assertNotNull(parsedIdToken.get("sub"), "No user logged in for " + application.getApplicationName()); - String loggedUser = keyValues.get(0).getValue(); - Assert.assertNotNull(loggedUser, "Logged user is null for " + application.getApplicationName()); - Assert.assertNotEquals(loggedUser, "null", "Logged user is null for " + application.getApplicationName()); - Assert.assertNotEquals(loggedUser, "", "Logged user is null for " + application.getApplicationName()); EntityUtils.consume(response.getEntity()); } @@ -376,14 +381,13 @@ protected void initUser() throws Exception { protected void initApplications() throws Exception { OIDCApplication playgroundApp = new OIDCApplication(OIDCUtilTest.playgroundAppOneAppName, - OIDCUtilTest.playgroundAppOneAppContext, OIDCUtilTest.playgroundAppOneAppCallBackUri); playgroundApp.addRequiredClaim(OIDCUtilTest.emailClaimUri); playgroundApp.addRequiredClaim(OIDCUtilTest.firstNameClaimUri); playgroundApp.addRequiredClaim(OIDCUtilTest.lastNameClaimUri); applications.put(OIDCUtilTest.playgroundAppOneAppName, playgroundApp); - playgroundApp = new OIDCApplication(OIDCUtilTest.playgroundAppTwoAppName, OIDCUtilTest.playgroundAppTwoAppContext, + playgroundApp = new OIDCApplication(OIDCUtilTest.playgroundAppTwoAppName, OIDCUtilTest.playgroundAppTwoAppCallBackUri); playgroundApp.addRequiredClaim(OIDCUtilTest.emailClaimUri); playgroundApp.addRequiredClaim(OIDCUtilTest.firstNameClaimUri); @@ -404,17 +408,4 @@ protected void deleteApplications() throws Exception { deleteApplication(entry.getValue()); } } - - protected HttpResponse sendGetAccessTokenPost(HttpClient client, OIDCApplication application) throws IOException { - - List urlParameters = new ArrayList<>(); - urlParameters.add(new BasicNameValuePair("callbackurl", application.getCallBackURL())); - urlParameters.add(new BasicNameValuePair("accessEndpoint", OAuth2Constant.ACCESS_TOKEN_ENDPOINT)); - urlParameters.add(new BasicNameValuePair("consumerSecret", application.getClientSecret())); - HttpResponse response = sendPostRequestWithParameters(client, urlParameters, String.format - (OIDCUtilTest.targetApplicationUrl, application.getApplicationContext() + OAuth2Constant.PlaygroundAppPaths - .accessTokenRequestPath)); - - return response; - } } diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oidc/OIDCAuthzCodeIdTokenValidationTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oidc/OIDCAuthzCodeIdTokenValidationTestCase.java index d1c411d748d..31dbae9f8ac 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oidc/OIDCAuthzCodeIdTokenValidationTestCase.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oidc/OIDCAuthzCodeIdTokenValidationTestCase.java @@ -45,15 +45,12 @@ import org.apache.http.impl.cookie.RFC6265CookieSpecProvider; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; -import org.hamcrest.collection.IsIn; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.carbon.automation.engine.context.TestUserMode; -import org.wso2.carbon.automation.test.utils.common.TestConfigurationProvider; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; -import org.wso2.identity.integration.common.utils.ISIntegrationTest; import org.wso2.identity.integration.test.oauth2.OAuth2ServiceAbstractIntegrationTest; import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.ApplicationPatchModel; import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.ApplicationResponseModel; @@ -64,15 +61,9 @@ import org.wso2.identity.integration.test.utils.OAuth2Constant; import org.wso2.identity.integration.test.utils.UserUtil; -import java.io.File; -import java.io.FileInputStream; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; -import java.security.KeyStore; -import java.security.cert.Certificate; -import java.security.cert.X509Certificate; -import java.security.interfaces.RSAPrivateKey; import java.util.ArrayList; import java.util.List; @@ -82,8 +73,6 @@ public class OIDCAuthzCodeIdTokenValidationTestCase extends OAuth2ServiceAbstractIntegrationTest { public static final String TEST_NONCE = "test_nonce"; - private RSAPrivateKey spPrivateKey; - private X509Certificate spX509PublicCert; private static final String CALLBACK_URL = "https://localhost/callback"; private CloseableHttpClient client; private String sessionDataKey; @@ -275,23 +264,4 @@ private String getLocationHeaderValue(HttpResponse response) { Assert.assertNotNull(location); return location.getValue(); } - - private void initServiceProviderKeys() throws Exception { - - KeyStore keyStore = KeyStore.getInstance(ISIntegrationTest.KEYSTORE_TYPE); - String pkcs12Path = TestConfigurationProvider.getResourceLocation("IS") + File.separator + "sp" + - File.separator + "keystores" + File.separator + "sp1KeyStore.p12"; - String pkcs12Password = "wso2carbon"; - - keyStore.load(new FileInputStream(pkcs12Path), pkcs12Password.toCharArray()); - - String alias = "wso2carbon"; - KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias, - new KeyStore.PasswordProtection(pkcs12Password.toCharArray())); - spPrivateKey = (RSAPrivateKey) pkEntry.getPrivateKey(); - - // Load certificate chain - Certificate[] chain = keyStore.getCertificateChain(alias); - spX509PublicCert = (X509Certificate) chain[0]; - } } diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oidc/OIDCRPInitiatedLogoutTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oidc/OIDCRPInitiatedLogoutTestCase.java index f9729d7711c..db6a2b48545 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oidc/OIDCRPInitiatedLogoutTestCase.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oidc/OIDCRPInitiatedLogoutTestCase.java @@ -32,6 +32,7 @@ import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; +import org.wso2.identity.integration.test.base.MockApplicationServer; import org.wso2.identity.integration.test.oidc.bean.OIDCApplication; import org.wso2.identity.integration.test.rest.api.user.common.model.Email; import org.wso2.identity.integration.test.rest.api.user.common.model.Name; @@ -45,6 +46,8 @@ import java.util.List; import java.util.Map; +import static org.wso2.identity.integration.test.utils.OAuth2Constant.AUTHORIZE_ENDPOINT_URL; + /** * This test class tests the OIDC RP-Initiated logout flows */ @@ -62,6 +65,7 @@ public class OIDCRPInitiatedLogoutTestCase extends OIDCAbstractIntegrationTest { protected List consentParameters = new ArrayList<>(); OIDCApplication playgroundAppOne; OIDCApplication playgroundAppTwo; + private MockApplicationServer mockApplicationServer; @BeforeClass(alwaysRun = true) public void testInit() throws Exception { @@ -88,6 +92,9 @@ public void testInit() throws Exception { .setDefaultCookieSpecRegistry(cookieSpecRegistry) .setDefaultRequestConfig(requestConfig) .build(); + + mockApplicationServer = new MockApplicationServer(); + mockApplicationServer.start(); } @AfterClass(alwaysRun = true) @@ -97,6 +104,7 @@ public void testClear() throws Exception { deleteApplication(playgroundAppOne); deleteApplication(playgroundAppTwo); clear(); + mockApplicationServer.stop(); } @AfterMethod @@ -145,12 +153,14 @@ public void testOIDCLogoutPrecedence() throws Exception { private void testInitiateOIDCRequest(OIDCApplication application, HttpClient client) throws Exception { - List urlParameters = OIDCUtilTest.getNameValuePairs(application); - HttpResponse response = sendPostRequestWithParameters(client, urlParameters, String.format - (OIDCUtilTest.targetApplicationUrl, application.getApplicationContext() + - OAuth2Constant.PlaygroundAppPaths.appUserAuthorizePath)); - Assert.assertNotNull(response, "Authorization request failed for " + application.getApplicationName() + - ". Authorized response is null."); + List urlParameters = new ArrayList<>(); + urlParameters.add(new BasicNameValuePair("response_type", OAuth2Constant.OAUTH2_GRANT_TYPE_CODE)); + urlParameters.add(new BasicNameValuePair("client_id", application.getClientId())); + urlParameters.add(new BasicNameValuePair("redirect_uri", application.getCallBackURL())); + urlParameters.add(new BasicNameValuePair("scope", "openid email profile")); + + HttpResponse response = sendPostRequestWithParameters(client, urlParameters, + getTenantQualifiedURL(AUTHORIZE_ENDPOINT_URL, tenantInfo.getDomain())); Header locationHeader = response.getFirstHeader(OAuth2Constant.HTTP_RESPONSE_HEADER_LOCATION); @@ -196,13 +206,8 @@ private void testOIDCLogin(OIDCApplication application, boolean checkConsent) th sessionDataKeyConsent = keyValues.get(0).getValue(); Assert.assertNotNull(sessionDataKeyConsent, "sessionDataKeyConsent is null."); } else { - keyPositionMap.put("Authorization Code", 1); - List keyValues = DataExtractUtil.extractTableRowDataFromResponse(response, - keyPositionMap); - Assert.assertNotNull(keyValues, "Authorization code not received for " + - application.getApplicationName()); - - authorizationCode = new AuthorizationCode(keyValues.get(0).getValue()); + authorizationCode = new AuthorizationCode( + mockApplicationServer.getAuthorizationCodeForApp(application.getApplicationName())); Assert.assertNotNull(authorizationCode, "Authorization code not received for " + application .getApplicationName()); } @@ -221,17 +226,8 @@ private void testOIDCConsentApproval(OIDCApplication application) throws Excepti EntityUtils.consume(response.getEntity()); response = sendPostRequest(client, locationHeader.getValue()); - Assert.assertNotNull(response, "Authorization code response is invalid for " + - application.getApplicationName()); - - Map keyPositionMap = new HashMap<>(1); - keyPositionMap.put("Authorization Code", 1); - List keyValues = DataExtractUtil.extractTableRowDataFromResponse(response, - keyPositionMap); - Assert.assertNotNull(keyValues, "Authorization code not received for " + - application.getApplicationName()); - - authorizationCode = new AuthorizationCode(keyValues.get(0).getValue()); + authorizationCode = new AuthorizationCode( + mockApplicationServer.getAuthorizationCodeForApp(application.getApplicationName())); Assert.assertNotNull(authorizationCode, "Authorization code not received for " + application .getApplicationName()); EntityUtils.consume(response.getEntity()); @@ -296,10 +292,8 @@ private void testOIDCLogout(boolean checkSuccess, OIDCApplication application, B Assert.assertTrue(redirectUrl.contains(application.getCallBackURL()), "Not redirected to the" + "post logout redirect url"); response = sendGetRequest(client, redirectUrl); - Assert.assertNotNull(response, "OIDC Logout failed."); - String result = DataExtractUtil.getContentData(response); - Assert.assertTrue(result.contains("WSO2 OAuth2 Playground"), "OIDC logout failed."); EntityUtils.consume(response.getEntity()); + mockApplicationServer.verifyLogoutRedirectionForApp(application.getApplicationName()); } else { Assert.assertTrue(redirectUrl.contains("oauth2_error.do")); } @@ -320,7 +314,6 @@ protected void initUser() { protected OIDCApplication initApplicationOne() { playgroundAppOne = new OIDCApplication(OIDCUtilTest.playgroundAppOneAppName, - OIDCUtilTest.playgroundAppOneAppContext, OIDCUtilTest.playgroundAppOneAppCallBackUri); playgroundAppOne.addRequiredClaim(OIDCUtilTest.emailClaimUri); playgroundAppOne.addRequiredClaim(OIDCUtilTest.firstNameClaimUri); @@ -330,7 +323,6 @@ protected OIDCApplication initApplicationOne() { protected OIDCApplication initApplicationTwo() { playgroundAppTwo = new OIDCApplication(OIDCUtilTest.playgroundAppTwoAppName, - OIDCUtilTest.playgroundAppTwoAppContext, OIDCUtilTest.playgroundAppTwoAppCallBackUri); playgroundAppOne.addRequiredClaim(OIDCUtilTest.emailClaimUri); playgroundAppOne.addRequiredClaim(OIDCUtilTest.firstNameClaimUri); diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oidc/OIDCSPWiseSkipLoginConsentTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oidc/OIDCSPWiseSkipLoginConsentTestCase.java index 20061ed6240..ac33d2b6ef7 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oidc/OIDCSPWiseSkipLoginConsentTestCase.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oidc/OIDCSPWiseSkipLoginConsentTestCase.java @@ -30,6 +30,7 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.carbon.automation.engine.context.TestUserMode; +import org.wso2.identity.integration.test.base.MockApplicationServer; import org.wso2.identity.integration.test.oidc.bean.OIDCApplication; import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.AdvancedApplicationConfiguration; import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.ApplicationPatchModel; @@ -46,6 +47,7 @@ public class OIDCSPWiseSkipLoginConsentTestCase extends OIDCAbstractIntegrationT private CookieStore cookieStore = new BasicCookieStore(); protected String sessionDataKey; protected String sessionDataKeyConsent; + private MockApplicationServer mockApplicationServer; @BeforeClass(alwaysRun = true) public void testInit() throws Exception { @@ -57,6 +59,9 @@ public void testInit() throws Exception { createApplications(); configureSPToSkipConsent(); client = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build(); + + mockApplicationServer = new MockApplicationServer(); + mockApplicationServer.start(); } @AfterClass(alwaysRun = true) @@ -64,6 +69,7 @@ public void clearObjects() throws Exception { deleteObjects(); clear(); + mockApplicationServer.stop(); } private void deleteObjects() throws Exception { @@ -83,16 +89,16 @@ private void configureSPToSkipConsent() throws Exception { @Test(groups = "wso2.is", description = "Test authz endpoint before creating a valid session") public void testCreateUserSession() throws Exception { - testSendAuthenticationRequest(OIDCUtilTest.applications.get(OIDCUtilTest.playgroundAppOneAppName), true, client, - cookieStore); + testSendAuthenticationRequest(OIDCUtilTest.applications.get(OIDCUtilTest.playgroundAppOneAppName), true, + client, cookieStore); testAuthentication(); } @Test(groups = "wso2.is", description = "Initiate authentication request from playground.apptwo") - public void testIntiateLoginRequestForAlreadyLoggedUser() throws Exception { + public void testInitiateLoginRequestForAlreadyLoggedUser() throws Exception { - testSendAuthenticationRequest(OIDCUtilTest.applications.get(OIDCUtilTest.playgroundAppTwoAppName), false, client - , cookieStore); + testSendAuthenticationRequest(OIDCUtilTest.applications.get(OIDCUtilTest.playgroundAppTwoAppName), false, + client, cookieStore); } private void testAuthentication() throws Exception { diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oidc/OIDCSSOConsentTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oidc/OIDCSSOConsentTestCase.java index e71147375b9..138cd18c3c6 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oidc/OIDCSSOConsentTestCase.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oidc/OIDCSSOConsentTestCase.java @@ -31,9 +31,11 @@ import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.cookie.RFC6265CookieSpecProvider; +import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.json.JSONObject; +import org.json.simple.JSONValue; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; @@ -41,6 +43,7 @@ import org.wso2.carbon.automation.engine.context.beans.Tenant; import org.wso2.carbon.automation.engine.context.beans.User; import org.apache.commons.lang.StringUtils; +import org.wso2.identity.integration.test.base.MockApplicationServer; import org.wso2.identity.integration.test.oidc.bean.OIDCApplication; import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.ApplicationPatchModel; import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.Claim; @@ -55,8 +58,11 @@ import org.wso2.identity.integration.test.utils.OAuth2Constant; import static org.apache.commons.lang.StringUtils.isBlank; +import static org.wso2.identity.integration.test.utils.OAuth2Constant.ACCESS_TOKEN_ENDPOINT; +import static org.wso2.identity.integration.test.utils.OAuth2Constant.AUTHORIZATION_HEADER; +import static org.wso2.identity.integration.test.utils.OAuth2Constant.AUTHORIZE_ENDPOINT_URL; +import static org.wso2.identity.integration.test.utils.OAuth2Constant.OAUTH2_GRANT_TYPE_AUTHORIZATION_CODE; -import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -81,6 +87,7 @@ public class OIDCSSOConsentTestCase extends OIDCAbstractIntegrationTest { protected List consentParameters = new ArrayList<>(); OIDCApplication playgroundApp; private String claimsToGetConsent; + private MockApplicationServer mockApplicationServer; @BeforeClass(alwaysRun = true) public void testInit() throws Exception { @@ -105,6 +112,9 @@ public void testInit() throws Exception { .setDefaultCookieSpecRegistry(cookieSpecRegistry) .setDefaultRequestConfig(requestConfig) .build(); + + mockApplicationServer = new MockApplicationServer(); + mockApplicationServer.start(); } @AfterClass(alwaysRun = true) @@ -113,6 +123,7 @@ public void testClear() throws Exception { deleteUser(user); deleteApplication(playgroundApp); clear(); + mockApplicationServer.stop(); } @Test(groups = "wso2.is", description = "Test consent management after updating " + @@ -140,17 +151,16 @@ public void testConsentWithAppClaimConfigUpdate() throws Exception { public void testSendAuthenticationRequest(OIDCApplication application, HttpClient client) throws Exception { - List urlParameters = OIDCUtilTest.getNameValuePairs(application); - HttpResponse response = sendPostRequestWithParameters(client, urlParameters, String.format - (OIDCUtilTest.targetApplicationUrl, application.getApplicationContext() + - OAuth2Constant.PlaygroundAppPaths.appUserAuthorizePath)); - Assert.assertNotNull(response, "Authorization request failed for " + application.getApplicationName() + - ". Authorized response is null."); + List urlParameters = new ArrayList<>(); + urlParameters.add(new BasicNameValuePair("response_type", OAuth2Constant.OAUTH2_GRANT_TYPE_CODE)); + urlParameters.add(new BasicNameValuePair("client_id", application.getClientId())); + urlParameters.add(new BasicNameValuePair("redirect_uri", application.getCallBackURL())); + + urlParameters.add(new BasicNameValuePair("scope", "openid email profile")); + HttpResponse response = sendPostRequestWithParameters(client, urlParameters, + getTenantQualifiedURL(AUTHORIZE_ENDPOINT_URL, tenantInfo.getDomain())); Header locationHeader = response.getFirstHeader(OAuth2Constant.HTTP_RESPONSE_HEADER_LOCATION); - - Assert.assertNotNull(locationHeader, "Authorization request failed for " + - application.getApplicationName() + ". Authorized response header is null."); EntityUtils.consume(response.getEntity()); response = sendGetRequest(client, locationHeader.getValue()); @@ -222,53 +232,41 @@ private void testConsentApproval(OIDCApplication application) throws Exception { EntityUtils.consume(response.getEntity()); response = sendPostRequest(client, locationHeader.getValue()); - Assert.assertNotNull(response, "Authorization code response is invalid for " + - application.getApplicationName()); - - Map keyPositionMap = new HashMap<>(1); - keyPositionMap.put("Authorization Code", 1); - List keyValues = DataExtractUtil.extractTableRowDataFromResponse(response, - keyPositionMap); - Assert.assertNotNull(keyValues, "Authorization code not received for " + - application.getApplicationName()); + EntityUtils.consume(response.getEntity()); - authorizationCode = keyValues.get(0).getValue(); + authorizationCode = mockApplicationServer.getAuthorizationCodeForApp(application.getApplicationName()); Assert.assertNotNull(authorizationCode, "Authorization code not received for " + application .getApplicationName()); - EntityUtils.consume(response.getEntity()); } private void testGetAccessToken(OIDCApplication application) throws Exception { - HttpResponse response = sendGetAccessTokenPost(client, application); - Assert.assertNotNull(response, "Access token response is invalid for " + - application.getApplicationName()); - EntityUtils.consume(response.getEntity()); - - response = sendPostRequest(client, String.format(OIDCUtilTest.targetApplicationUrl, - application.getApplicationContext() + OAuth2Constant.PlaygroundAppPaths.appAuthorizePath)); - - Map keyPositionMap = new HashMap<>(1); - keyPositionMap.put("name=\"accessToken\"", 1); - List keyValues = DataExtractUtil.extractInputValueFromResponse(response, - keyPositionMap); - Assert.assertNotNull(keyValues, "Access token not received for " + application.getApplicationName()); - - accessToken = keyValues.get(0).getValue(); - Assert.assertNotNull(accessToken, "Access token not received for " + application.getApplicationName()); - EntityUtils.consume(response.getEntity()); - - response = sendPostRequest(client, String.format(OIDCUtilTest.targetApplicationUrl, - application.getApplicationContext() + OAuth2Constant.PlaygroundAppPaths.appAuthorizePath)); - - keyPositionMap = new HashMap<>(1); - keyPositionMap.put("id=\"loggedUser\"", 1); - keyValues = DataExtractUtil.extractLabelValueFromResponse(response, keyPositionMap); - Assert.assertNotNull(keyValues, "No user logged in for " + application.getApplicationName()); - - String loggedUser = keyValues.get(0).getValue(); - Assert.assertNotNull(loggedUser, "Logged user is null for " + application.getApplicationName()); - EntityUtils.consume(response.getEntity()); + List urlParameters = new ArrayList<>(); + urlParameters.add(new BasicNameValuePair("code", authorizationCode)); + urlParameters.add(new BasicNameValuePair("grant_type", OAUTH2_GRANT_TYPE_AUTHORIZATION_CODE)); + urlParameters.add(new BasicNameValuePair("redirect_uri", application.getCallBackURL())); + urlParameters.add(new BasicNameValuePair("client_id", application.getClientSecret())); + + urlParameters.add(new BasicNameValuePair("scope", "openid")); + + List
headers = new ArrayList<>(); + headers.add(new BasicHeader(AUTHORIZATION_HEADER, + OAuth2Constant.BASIC_HEADER + " " + getBase64EncodedString(application.getClientId(), + application.getClientSecret()))); + headers.add(new BasicHeader("Content-Type", "application/x-www-form-urlencoded")); + headers.add(new BasicHeader("User-Agent", OAuth2Constant.USER_AGENT)); + + HttpResponse response = sendPostRequest(client, headers, urlParameters, + getTenantQualifiedURL(ACCESS_TOKEN_ENDPOINT, tenantInfo.getDomain())); + String responseString = EntityUtils.toString(response.getEntity()); + Map responseMap = (Map) JSONValue.parse(responseString); + accessToken = (String) responseMap.get("access_token"); + + String idToken = (String) responseMap.get("id_token"); + String[] tokenParts = idToken.split("\\."); + String payload = new String(java.util.Base64.getUrlDecoder().decode(tokenParts[1])); + Map parsedIdToken = (Map) JSONValue.parse(payload); + Assert.assertNotNull(parsedIdToken.get("sub"), "No user logged in for " + application.getApplicationName()); } protected void initUser() throws Exception { @@ -283,7 +281,6 @@ protected void initUser() throws Exception { protected OIDCApplication initApplication() { playgroundApp = new OIDCApplication(OIDCUtilTest.playgroundAppOneAppName, - OIDCUtilTest.playgroundAppOneAppContext, OIDCUtilTest.playgroundAppOneAppCallBackUri); playgroundApp.addRequiredClaim(OIDCUtilTest.emailClaimUri); playgroundApp.addRequiredClaim(OIDCUtilTest.firstNameClaimUri); @@ -306,19 +303,6 @@ private void updateApplication(OIDCApplication playgroundApp) throws Exception { updateApplication(playgroundApp.getApplicationId(), new ApplicationPatchModel().claimConfiguration(claimConfig)); } - protected HttpResponse sendGetAccessTokenPost(HttpClient client, OIDCApplication application) throws IOException { - - List urlParameters = new ArrayList<>(); - urlParameters.add(new BasicNameValuePair("callbackurl", application.getCallBackURL())); - urlParameters.add(new BasicNameValuePair("accessEndpoint", OAuth2Constant.ACCESS_TOKEN_ENDPOINT)); - urlParameters.add(new BasicNameValuePair("consumerSecret", application.getClientSecret())); - HttpResponse response = sendPostRequestWithParameters(client, urlParameters, String.format - (OIDCUtilTest.targetApplicationUrl, application.getApplicationContext() + - OAuth2Constant.PlaygroundAppPaths.accessTokenRequestPath)); - - return response; - } - private void performOIDCLogout() { try { diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oidc/OIDCUtilTest.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oidc/OIDCUtilTest.java index 9fd38e90710..8a5f866d25b 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oidc/OIDCUtilTest.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oidc/OIDCUtilTest.java @@ -22,6 +22,7 @@ import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.message.BasicNameValuePair; +import org.wso2.identity.integration.test.base.MockApplicationServer; import org.wso2.identity.integration.test.oidc.bean.OIDCApplication; import org.wso2.identity.integration.test.rest.api.user.common.model.Email; import org.wso2.identity.integration.test.rest.api.user.common.model.Name; @@ -54,17 +55,11 @@ public class OIDCUtilTest { public static final String profile = "default"; protected static String sessionDataKey; - public static final String playgroundAppOneAppName = "playground.appone"; - public static final String playgroundAppOneAppCallBackUri = "http://localhost:" + TOMCAT_PORT + "/playground" + "" + - ".appone/oauth2client"; - public static final String playgroundAppOneAppContext = "/playground.appone"; + public static final String playgroundAppOneAppName = MockApplicationServer.Constants.APP1.NAME; + public static final String playgroundAppOneAppCallBackUri = MockApplicationServer.Constants.APP1.CALLBACK_URL; - public static final String playgroundAppTwoAppName = "playground.apptwo"; - public static final String playgroundAppTwoAppCallBackUri = "http://localhost:" + TOMCAT_PORT + "/playground" + "" + - ".apptwo/oauth2client"; - public static final String playgroundAppTwoAppContext = "/playground.apptwo"; - - public static final String targetApplicationUrl = "http://localhost:" + TOMCAT_PORT + "%s"; + public static final String playgroundAppTwoAppName = MockApplicationServer.Constants.APP2.NAME; + public static final String playgroundAppTwoAppCallBackUri = MockApplicationServer.Constants.APP2.CALLBACK_URL; public static final String emailClaimUri = "http://wso2.org/claims/emailaddress"; public static final String firstNameClaimUri = "http://wso2.org/claims/givenname"; @@ -87,14 +82,14 @@ public static void initUser() { */ public static void initApplications() { - OIDCApplication playgroundApp = new OIDCApplication(playgroundAppOneAppName, playgroundAppOneAppContext, + OIDCApplication playgroundApp = new OIDCApplication(playgroundAppOneAppName, playgroundAppOneAppCallBackUri); playgroundApp.addRequiredClaim(emailClaimUri); playgroundApp.addRequiredClaim(firstNameClaimUri); playgroundApp.addRequiredClaim(lastNameClaimUri); applications.put(playgroundAppOneAppName, playgroundApp); - playgroundApp = new OIDCApplication(playgroundAppTwoAppName, playgroundAppTwoAppContext, + playgroundApp = new OIDCApplication(playgroundAppTwoAppName, playgroundAppTwoAppCallBackUri); playgroundApp.addRequiredClaim(emailClaimUri); playgroundApp.addRequiredClaim(firstNameClaimUri); diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oidc/bean/OIDCApplication.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oidc/bean/OIDCApplication.java index c42ecbc0e9e..a71263f1109 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oidc/bean/OIDCApplication.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/oidc/bean/OIDCApplication.java @@ -27,7 +27,6 @@ public class OIDCApplication { private String applicationName; private String clientId; private String clientSecret; - private String applicationContext; private String callBackURL; private String subjectClaimURI; private List requiredClaims = null; @@ -36,9 +35,8 @@ public OIDCApplication() { } - public OIDCApplication(String applicationName, String applicationContext, String callBackURL) { + public OIDCApplication(String applicationName, String callBackURL) { this.applicationName = applicationName; - this.applicationContext = applicationContext; this.callBackURL = callBackURL; } @@ -74,14 +72,6 @@ public void setClientSecret(String clientSecret) { this.clientSecret = clientSecret; } - public String getApplicationContext() { - return applicationContext; - } - - public void setApplicationContext(String applicationContext) { - this.applicationContext = applicationContext; - } - public String getCallBackURL() { return callBackURL; } diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/openid/MasterOpenIDInitiator.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/openid/MasterOpenIDInitiator.java deleted file mode 100644 index 4c593462350..00000000000 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/openid/MasterOpenIDInitiator.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - *Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - *WSO2 Inc. licenses this file to you under the Apache License, - *Version 2.0 (the "License"); you may not use this file except - *in compliance with the License. - *You may obtain a copy of the License at - * - *http://www.apache.org/licenses/LICENSE-2.0 - * - *Unless required by applicable law or agreed to in writing, - *software distributed under the License is distributed on an - *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - *KIND, either express or implied. See the License for the - *specific language governing permissions and limitations - *under the License. - */ -package org.wso2.identity.integration.test.openid; - -import org.apache.axis2.AxisFault; -import org.wso2.identity.integration.common.clients.openid.OpenIDProviderServiceClient; -import org.wso2.identity.integration.common.clients.usermgt.remote.RemoteUserStoreManagerServiceClient; - -public class MasterOpenIDInitiator { - - protected OpenIDProviderServiceClient openidServiceClient = null; - protected RemoteUserStoreManagerServiceClient remoteUSMServiceClient = null; - - protected void init(int userId) throws AxisFault { -// EnvironmentBuilder builder = new EnvironmentBuilder(); -// isEnvironment = builder.build().getIs(); -// userInfo = UserListCsvReader.getUserInfo(userId); -// String backEndUrl = isEnvironment.getBackEndUrl(); -// String sessionCookie = isEnvironment.getSessionCookie(); -// openidServiceClient = new OpenIDProviderServiceClient(backEndUrl, sessionCookie); -// remoteUSMServiceClient = new RemoteUserStoreManagerServiceClient(backEndUrl, sessionCookie); - } -} \ No newline at end of file diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/openid/OpenIDAuthenticationTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/openid/OpenIDAuthenticationTestCase.java deleted file mode 100644 index 6a24f8dae61..00000000000 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/openid/OpenIDAuthenticationTestCase.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - *Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - *WSO2 Inc. licenses this file to you under the Apache License, - *Version 2.0 (the "License"); you may not use this file except - *in compliance with the License. - *You may obtain a copy of the License at - * - *http://www.apache.org/licenses/LICENSE-2.0 - * - *Unless required by applicable law or agreed to in writing, - *software distributed under the License is distributed on an - *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - *KIND, either express or implied. See the License for the - *specific language governing permissions and limitations - *under the License. - */ -package org.wso2.identity.integration.test.openid; - -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.carbon.identity.provider.openid.stub.dto.OpenIDRememberMeDTO; -import org.wso2.identity.integration.common.clients.openid.OpenIDProviderServiceClient; -import org.wso2.identity.integration.common.utils.ISIntegrationTest; - -public class OpenIDAuthenticationTestCase extends ISIntegrationTest { - - OpenIDProviderServiceClient openidServiceClient; - String adminUserName; - String adminPassword; - - @BeforeClass(alwaysRun = true) - public void testInit() throws Exception { - super.init(); - - openidServiceClient = new OpenIDProviderServiceClient(backendURL, sessionCookie); - adminUserName = userInfo.getUserName(); - adminPassword = userInfo.getPassword(); - } - - @AfterClass(alwaysRun = true) - public void atEnd() throws Exception { - - openidServiceClient = null; - } - - @Test(alwaysRun = true, description = "Authenticate with Password") - public void testOpenidPasswordAuthentication() { - - String openId = Util.getDefaultOpenIDIdentifier(adminUserName); - - boolean isAuthenticated = false; - - try { - isAuthenticated = openidServiceClient.authenticateWithOpenID(openId, adminPassword); - } catch (Exception e) { - Assert.fail("Error while authenticating", e); - } - - Assert.assertTrue(isAuthenticated); - } - - @Test(alwaysRun = true, description = "Authenticate with Remember ME", dependsOnMethods="testOpenidPasswordAuthentication") - public void testOpenidRememberMeAuthentication() { - - // first authenticate without a cookie - String openID = Util.getDefaultOpenIDIdentifier(adminUserName); - OpenIDRememberMeDTO rememberMeDTO = null; - - try { - rememberMeDTO = openidServiceClient.authenticateWithOpenIDRememberMe(openID, adminPassword, "127.0.0.1", null); - } catch (Exception e) { - Assert.fail("Error while authenticating with remember me", e); - } - - Assert.assertTrue(rememberMeDTO.getAuthenticated()); - - // now lets authenticate with remember me - - String cookie = rememberMeDTO.getNewCookieValue(); - - OpenIDRememberMeDTO newRememberMeDTO = null; - - try { - newRememberMeDTO = openidServiceClient.authenticateWithOpenIDRememberMe(openID, null, "127.0.0.1", cookie); - } catch (Exception e) { - Assert.fail("Error while authenticating with remember me cookie", e); - } - - Assert.assertTrue(newRememberMeDTO.getAuthenticated()); - - } - -} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/openid/OpenIDProviderServerConfigTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/openid/OpenIDProviderServerConfigTestCase.java deleted file mode 100644 index 3ba83a73901..00000000000 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/openid/OpenIDProviderServerConfigTestCase.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - *Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - *WSO2 Inc. licenses this file to you under the Apache License, - *Version 2.0 (the "License"); you may not use this file except - *in compliance with the License. - *You may obtain a copy of the License at - * - *http://www.apache.org/licenses/LICENSE-2.0 - * - *Unless required by applicable law or agreed to in writing, - *software distributed under the License is distributed on an - *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - *KIND, either express or implied. See the License for the - *specific language governing permissions and limitations - *under the License. - */ -package org.wso2.identity.integration.test.openid; - -import java.rmi.RemoteException; - -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.carbon.identity.provider.openid.stub.dto.OpenIDProviderInfoDTO; -import org.wso2.identity.integration.common.clients.openid.OpenIDProviderServiceClient; -import org.wso2.identity.integration.common.utils.ISIntegrationTest; - -public class OpenIDProviderServerConfigTestCase extends ISIntegrationTest { - - OpenIDProviderServiceClient openidServiceClient; - String adminUserName; - - @BeforeClass(alwaysRun = true) - public void testInit() throws Exception { - super.init(); - - openidServiceClient = new OpenIDProviderServiceClient(backendURL, sessionCookie); - adminUserName = userInfo.getUserName(); - } - - @AfterClass(alwaysRun = true) - public void atEnd() throws Exception { - openidServiceClient = null; - } - - - @Test(alwaysRun = true, description = "Testing Provider Info") - public void testProviderInfo() { - - OpenIDProviderInfoDTO providerInfo = null; - - try { - providerInfo = openidServiceClient.getOpenIDProviderInfo(adminUserName, - Util.getDefaultOpenIDIdentifier(adminUserName)); - } catch (Exception e) { - Assert.fail("Error while getting OpenID Provider Info", e); - } - - Assert.assertEquals(providerInfo.getOpenID(), "https://localhost:9853/openid/admin"); - - Assert.assertEquals(providerInfo.getOpenIDProviderServerUrl(), "https://localhost:9853/openidserver"); - } - - @Test(alwaysRun = true, description = "Test Session Timeout", dependsOnMethods = "testProviderInfo") - public void testSessionTimeOut() { - - int sessionTimeout = 0; - try { - sessionTimeout = openidServiceClient.getOpenIDSessionTimeout(); - } catch (RemoteException e) { - Assert.fail("Error while getting session timeout", e); - } - - Assert.assertEquals(sessionTimeout, 36000); - } - - @Test(alwaysRun = true, description = "Check SkipUserConsent", dependsOnMethods = "testSessionTimeOut") - public void testSkipUserConsent() { - - boolean isSkipped = true; - try { - isSkipped = openidServiceClient.isOpenIDUserApprovalBypassEnabled(); - } catch (RemoteException e) { - Assert.fail("Error while reading SkipUserConsent config", e); - } - - Assert.assertFalse(isSkipped); - } -} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/openid/OpenIDRPManagementTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/openid/OpenIDRPManagementTestCase.java deleted file mode 100644 index 20127507556..00000000000 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/openid/OpenIDRPManagementTestCase.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - *Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - *WSO2 Inc. licenses this file to you under the Apache License, - *Version 2.0 (the "License"); you may not use this file except - *in compliance with the License. - *You may obtain a copy of the License at - * - *http://www.apache.org/licenses/LICENSE-2.0 - * - *Unless required by applicable law or agreed to in writing, - *software distributed under the License is distributed on an - *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - *KIND, either express or implied. See the License for the - *specific language governing permissions and limitations - *under the License. - */ -package org.wso2.identity.integration.test.openid; - -import java.util.Calendar; -import java.util.Date; - -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.carbon.identity.provider.openid.stub.dto.OpenIDUserRPDTO; -import org.wso2.identity.integration.common.clients.openid.OpenIDProviderServiceClient; -import org.wso2.identity.integration.common.utils.ISIntegrationTest; - -public class OpenIDRPManagementTestCase extends ISIntegrationTest { - - OpenIDProviderServiceClient openidServiceClient; - - private String userName = "admin"; - private String profileName = "default"; - - private String rp1Url = "http://localhost:8490/openidclient"; - private boolean rp1TrustedAlways = false; - private int rp1VisitCount = 0; - private Date rp1lastVisit = Calendar.getInstance().getTime(); - - private String rp2Url = "http://localhost:8490/openidclient2"; - private boolean rp2TrustedAlways = true; - private int rp2VisitCount = 1; - private Date rp2lastVisit = Calendar.getInstance().getTime(); - - @BeforeClass(alwaysRun = true) - public void testInit() throws Exception { - super.init(); - - openidServiceClient = new OpenIDProviderServiceClient(backendURL, sessionCookie); - } - - @AfterClass(alwaysRun = true) - public void atEnd() throws Exception { - openidServiceClient = null; - } - - @Test(alwaysRun = true, description = "Authenticate with Password") - public void testOpenidRPAddUpdate() { - - // add rp1 - OpenIDUserRPDTO rp1dto = new OpenIDUserRPDTO(); - rp1dto.setDefaultProfileName(profileName); - rp1dto.setUserName(userName); - rp1dto.setOpenID(Util.getDefaultOpenIDIdentifier(userName)); - rp1dto.setRpUrl(rp1Url); - rp1dto.setTrustedAlways(rp1TrustedAlways); - rp1dto.setVisitCount(rp1VisitCount); - rp1dto.setLastVisit(rp1lastVisit); - - try { - openidServiceClient.updateOpenIDUserRPInfo(rp1dto); - } catch (Exception e) { - Assert.fail("Error while updating user RPInfo", e); - } - - // add rp2 - OpenIDUserRPDTO rp2dto = new OpenIDUserRPDTO(); - rp2dto.setDefaultProfileName(profileName); - rp2dto.setUserName(userName); - rp2dto.setOpenID(Util.getDefaultOpenIDIdentifier(userName)); - rp2dto.setRpUrl(rp2Url); - rp2dto.setTrustedAlways(rp2TrustedAlways); - rp2dto.setVisitCount(rp2VisitCount); - rp2dto.setLastVisit(rp2lastVisit); - - try { - openidServiceClient.updateOpenIDUserRPInfo(rp2dto); - } catch (Exception e) { - Assert.fail("Error while updating user RPInfo", e); - } - - // reading rps back - OpenIDUserRPDTO[] rps = null; - - try { - rps = openidServiceClient.getOpenIDUserRPs(Util.getDefaultOpenIDIdentifier(userName)); - } catch (Exception e) { - Assert.fail("Error while getting user RPs", e); - } - - // we should get two rps - Assert.assertEquals(rps.length, 2); - - // lets read values back and check - for(OpenIDUserRPDTO rp : rps) { - - if(rp1Url.equals(rp.getRpUrl())) { - Assert.assertEquals(rp.getTrustedAlways(), rp1TrustedAlways); - Assert.assertEquals(rp.getUserName(), userName); - - } else if(rp2Url.equals(rp.getRpUrl())) { - Assert.assertEquals(rp.getTrustedAlways(), rp2TrustedAlways); - Assert.assertEquals(rp.getUserName(), userName); - - } else { - Assert.fail("Invalid RP returned"); - } - - } - - // update the RP1, lets trust it always - rp1TrustedAlways = true; - rp1VisitCount++; - rp1lastVisit = Calendar.getInstance().getTime(); - - // update rp1 - OpenIDUserRPDTO rp1Updateddto = new OpenIDUserRPDTO(); - rp1Updateddto.setDefaultProfileName(profileName); - rp1Updateddto.setUserName(userName); - rp1Updateddto.setOpenID(Util.getDefaultOpenIDIdentifier(userName)); - rp1Updateddto.setRpUrl(rp1Url); - rp1Updateddto.setTrustedAlways(rp1TrustedAlways); - rp1Updateddto.setVisitCount(rp1VisitCount); - rp1Updateddto.setLastVisit(rp1lastVisit); - try { - openidServiceClient.updateOpenIDUserRPInfo(rp1Updateddto); - } catch (Exception e) { - Assert.fail("Error while updating user RPInfo", e); - } - - // read the RP1 back now - OpenIDUserRPDTO rp1updted = null; - try { - rp1updted = openidServiceClient.getOpenIDUserRPInfo(Util.getDefaultOpenIDIdentifier(userName), rp1Url); - } catch (Exception e) { - Assert.fail("Error while updating user RPInfo", e); - } - - Assert.assertEquals(rp1updted.getRpUrl(), rp1Url); - - Assert.assertEquals(rp1updted.getTrustedAlways(), rp1TrustedAlways); - - } - -} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/openid/OpenIDSSOTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/openid/OpenIDSSOTestCase.java deleted file mode 100644 index 51bce7c5df1..00000000000 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/openid/OpenIDSSOTestCase.java +++ /dev/null @@ -1,475 +0,0 @@ -/* - * Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.identity.integration.test.openid; - -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.Header; -import org.apache.http.HttpResponse; -import org.apache.http.NameValuePair; -import org.apache.http.client.config.CookieSpecs; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.entity.UrlEncodedFormEntity; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.config.Lookup; -import org.apache.http.config.RegistryBuilder; -import org.apache.http.cookie.CookieSpecProvider; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.cookie.RFC6265CookieSpecProvider; -import org.apache.http.message.BasicNameValuePair; -import org.apache.http.util.EntityUtils; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Factory; -import org.testng.annotations.Test; -import org.wso2.carbon.integration.common.utils.mgt.ServerConfigurationManager; -import org.wso2.carbon.um.ws.api.stub.ClaimValue; -import org.wso2.identity.integration.common.clients.usermgt.remote.RemoteUserStoreManagerServiceClient; -import org.wso2.identity.integration.common.utils.ISIntegrationTest; -import org.wso2.identity.integration.test.util.Utils; - -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class OpenIDSSOTestCase extends ISIntegrationTest { - private static final Log log = LogFactory.getLog(OpenIDSSOTestCase.class); - - private static final String USER_AGENT = "Apache-HttpClient/4.2.5 (java 1.6)"; - private static final String COMMON_AUTH_URL = "https://localhost:9853/commonauth"; - private static final String OPEN_ID_PROFILE_URL = "https://localhost:9853/authenticationendpoint/openid_profile.do"; - private static final String APPROVAL_URL = "https://localhost:9853/openidserver"; - private static final String OPEN_ID_URL = "http://localhost:8490/%s/openid?OpenId" + - ".ClaimedId=https://localhost:9853/openid/"; - //Claim Uris - private static final String firstNameClaimURI = "http://axschema.org/namePerson/first"; - private static final String emailClaimURI = "http://axschema.org/contact/email"; - private static final String lastNameClaimURI = "http://wso2.org/claims/lastname"; - private static final String profileName = "default"; - - private OpenIDUtils.OpenIDConfig config; - private RemoteUserStoreManagerServiceClient remoteUSMServiceClient; - private Lookup cookieSpecRegistry; - private RequestConfig requestConfig; - private CloseableHttpClient client; - private File identityXML; - private ServerConfigurationManager serverConfigurationManager; - - @Factory(dataProvider = "openIdConfigBeanProvider") - public OpenIDSSOTestCase(OpenIDUtils.OpenIDConfig configBean) { - if (log.isDebugEnabled()){ - log.info("OpenId Test initialized for " + configBean); - } - - this.config = configBean; - } - - @BeforeClass(alwaysRun = true) - public void init() throws Exception { - super.init(); - - if (config.getUserConsent() == OpenIDUtils.UserConsent.SKIP){ - changeISConfiguration(); - super.init(); - } - - remoteUSMServiceClient = new RemoteUserStoreManagerServiceClient(backendURL, sessionCookie); - } - - @AfterClass(alwaysRun = true) - public void clear() throws Exception{ - if (config.getUserConsent() == OpenIDUtils.UserConsent.SKIP){ - resetISConfiguration(); - } - - remoteUSMServiceClient = null; - client.close(); - } - - @BeforeMethod - public void createUser(){ - OpenIDUtils.User user = config.getUser(); - - log.info("Creating User " + user.getUsername()); - - ClaimValue firstName = new ClaimValue(); - firstName.setClaimURI(firstNameClaimURI); - firstName.setValue(user.getUsername()); - - ClaimValue lastName = new ClaimValue(); - lastName.setClaimURI(lastNameClaimURI); - lastName.setValue(user.getUsername()); - - ClaimValue email = new ClaimValue(); - email.setClaimURI(emailClaimURI); - email.setValue(user.getEmail()); - - try { - // creating the user - remoteUSMServiceClient.addUser(user.getUsername(), user.getPassword(), - new String[]{user.getRole()}, new ClaimValue[]{email, firstName, lastName}, - profileName, true); - } catch (Exception e) { - Assert.fail("Error while creating the user", e); - } - - } - - @AfterMethod - public void deleteUser(){ - log.info("Deleting User " + config.getUser().getUsername()); - try { - remoteUSMServiceClient.deleteUser(config.getUser().getUsername()); - } catch (Exception e) { - Assert.fail("Error while deleting the user", e); - } - } - - @Test(alwaysRun = true, groups = "wso2.is", description = "Testing OpenId sample parameterized test") - public void testOpenId() throws IOException { - if (log.isDebugEnabled()){ - log.debug("Executing Test Case for " + config); - } - - HttpResponse response; - String results; - - cookieSpecRegistry = RegistryBuilder.create() - .register(CookieSpecs.DEFAULT, new RFC6265CookieSpecProvider()) - .build(); - requestConfig = RequestConfig.custom() - .setCookieSpec(CookieSpecs.DEFAULT) - .build(); - client = HttpClientBuilder.create() - .setDefaultCookieSpecRegistry(cookieSpecRegistry) - .setDefaultRequestConfig(requestConfig) - .build(); - - response = executePhaseBeforeApproval(); - - if (config.getUserConsent() != OpenIDUtils.UserConsent.SKIP) { - response = executePhaseAfterApproval(response); - } - - results = extractDataFromResponse(response); - - assertLogin(results); - - if (config.getAppType() == OpenIDUtils.AppType.SMART_WITH_CLAIMS || - config.getAppType() == OpenIDUtils.AppType.DUMB_WITH_CLAIMS){ - assertAttributes(results); - } - - if (config.getUserConsent() == OpenIDUtils.UserConsent.APPROVE_ALWAYS){ - client = HttpClientBuilder.create() - .setDefaultCookieSpecRegistry(cookieSpecRegistry) - .setDefaultRequestConfig(requestConfig) - .build(); - - response = executePhaseBeforeApproval(); - results = extractDataFromResponse(response); - - assertLogin(results); - } - } - - private HttpResponse executePhaseBeforeApproval() throws IOException { - HttpResponse response; - String sessionKey; - Map keyPositionMap; - - response = sendOpenIdGet(); - keyPositionMap = new HashMap(1); - keyPositionMap.put("name=\"sessionDataKey\"", 1); - sessionKey = extractDataFromResponse(response, keyPositionMap).get(0).getValue(); - - response = sendLoginPost(sessionKey); - EntityUtils.consume(response.getEntity()); - - return sendRedirectGet(response); - } - - private HttpResponse executePhaseAfterApproval(HttpResponse response) throws IOException { - Map keyPositionMap; - List keyValues; - - keyPositionMap = new HashMap(); - keyPositionMap.put("openid.identity", 5); - keyPositionMap.put("openid.return_to", 5); - keyPositionMap.put("claimTag", 5); - keyPositionMap.put("claimValue", 5); - - keyValues = extractDataFromResponse(response,keyPositionMap); - assertClaims(keyValues); - - response = sendOpenIdProfilePost(keyValues); - EntityUtils.consume(response.getEntity()); - - response = sendApprovalPost(); - EntityUtils.consume(response.getEntity()); - - return sendRedirectGet(response); - } - - @DataProvider(name = "openIdConfigBeanProvider") - public static OpenIDUtils.OpenIDConfig[][] openIdConfigBeanProvider(){ - return new OpenIDUtils.OpenIDConfig[][]{ - {new OpenIDUtils.OpenIDConfig(OpenIDUtils.User.ADMIN, - OpenIDUtils.UserConsent.APPROVE, OpenIDUtils.AppType.SMART_WITH_CLAIMS)}, - {new OpenIDUtils.OpenIDConfig(OpenIDUtils.User.ADMIN, - OpenIDUtils.UserConsent.APPROVE, OpenIDUtils.AppType.SMART_WITHOUT_CLAIMS)}, - {new OpenIDUtils.OpenIDConfig(OpenIDUtils.User.ADMIN, - OpenIDUtils.UserConsent.APPROVE, OpenIDUtils.AppType.DUMB_WITH_CLAIMS)}, - {new OpenIDUtils.OpenIDConfig(OpenIDUtils.User.ADMIN, - OpenIDUtils.UserConsent.APPROVE, OpenIDUtils.AppType.DUMB_WITHOUT_CLAIMS)}, - {new OpenIDUtils.OpenIDConfig(OpenIDUtils.User.USER1, - OpenIDUtils.UserConsent.APPROVE, OpenIDUtils.AppType.SMART_WITH_CLAIMS)}, - {new OpenIDUtils.OpenIDConfig(OpenIDUtils.User.USER1, - OpenIDUtils.UserConsent.APPROVE, OpenIDUtils.AppType.SMART_WITHOUT_CLAIMS)}, - {new OpenIDUtils.OpenIDConfig(OpenIDUtils.User.USER1, - OpenIDUtils.UserConsent.APPROVE, OpenIDUtils.AppType.DUMB_WITH_CLAIMS)}, - {new OpenIDUtils.OpenIDConfig(OpenIDUtils.User.USER1, - OpenIDUtils.UserConsent.APPROVE, OpenIDUtils.AppType.DUMB_WITHOUT_CLAIMS)}, - {new OpenIDUtils.OpenIDConfig(OpenIDUtils.User.USER2, - OpenIDUtils.UserConsent.APPROVE_ALWAYS, OpenIDUtils.AppType.SMART_WITH_CLAIMS)}, - {new OpenIDUtils.OpenIDConfig(OpenIDUtils.User.USER2, - OpenIDUtils.UserConsent.APPROVE_ALWAYS, OpenIDUtils.AppType.SMART_WITHOUT_CLAIMS)}, - {new OpenIDUtils.OpenIDConfig(OpenIDUtils.User.USER2, - OpenIDUtils.UserConsent.APPROVE_ALWAYS, OpenIDUtils.AppType.DUMB_WITH_CLAIMS)}, - {new OpenIDUtils.OpenIDConfig(OpenIDUtils.User.USER2, - OpenIDUtils.UserConsent.APPROVE_ALWAYS, OpenIDUtils.AppType.DUMB_WITHOUT_CLAIMS)}, - /*{new OpenIDUtils.OpenIDConfig(OpenIDUtils.User.USER1, - OpenIDUtils.UserConsent.SKIP, OpenIDUtils.AppType.SMART_WITH_CLAIMS)}, - {new OpenIDUtils.OpenIDConfig(OpenIDUtils.User.USER1, - OpenIDUtils.UserConsent.SKIP, OpenIDUtils.AppType.SMART_WITHOUT_CLAIMS)}, - {new OpenIDUtils.OpenIDConfig(OpenIDUtils.User.USER1, - OpenIDUtils.UserConsent.SKIP, OpenIDUtils.AppType.DUMB_WITH_CLAIMS)}, - {new OpenIDUtils.OpenIDConfig(OpenIDUtils.User.USER1, - OpenIDUtils.UserConsent.SKIP, OpenIDUtils.AppType.DUMB_WITHOUT_CLAIMS)},*/ - }; - } - - private List extractDataFromResponse(HttpResponse response, Map keyPositionMap) throws IOException { - List keyValues = new ArrayList(); - BufferedReader rd = new BufferedReader( - new InputStreamReader(response.getEntity().getContent())); - String line; - while ((line = rd.readLine()) != null) { - for (String key: keyPositionMap.keySet()){ - if (line.contains(key)) { - String[] tokens = line.split("'"); - KeyValue keyValue = new KeyValue(key, tokens[keyPositionMap.get(key)]); - keyValues.add(keyValue); - } - } - } - rd.close(); - - return keyValues; - } - - private String extractDataFromResponse(HttpResponse response) throws IOException { - StringBuilder sb = new StringBuilder(); - BufferedReader rd = new BufferedReader( - new InputStreamReader(response.getEntity().getContent())); - String line; - while ((line = rd.readLine()) != null) { - sb.append(line); - } - rd.close(); - return sb.toString(); - } - - private HttpResponse sendOpenIdGet() throws IOException { - HttpGet request = new HttpGet(String.format(OPEN_ID_URL, config.getAppType().getArtifact())); - request.addHeader("User-Agent", USER_AGENT); - - return client.execute(request); - } - - private HttpResponse sendLoginPost(String sessionKey) throws IOException { - HttpPost request = new HttpPost(COMMON_AUTH_URL); - request.setHeader("User-Agent", USER_AGENT); - - List urlParameters = new ArrayList(); - urlParameters.add(new BasicNameValuePair("username", config.getUser().getUsername() + "@" + tenantInfo.getDomain())); - urlParameters.add(new BasicNameValuePair("password", config.getUser().getPassword())); - urlParameters.add(new BasicNameValuePair("sessionDataKey", sessionKey)); - - request.setEntity(new UrlEncodedFormEntity(urlParameters)); - - return client.execute(request); - } - - private HttpResponse sendRedirectGet(HttpResponse response) throws IOException { - Header[] headers = response.getAllHeaders(); - String url = ""; - for (Header header : headers) { - if ("Location".equals(header.getName())) { - url = header.getValue(); - } - } - - url = StringUtils.replace(url, "/t/" + tenantInfo.getDomain(), ""); - HttpGet request = new HttpGet(url); - request.addHeader("User-Agent", USER_AGENT); - - return client.execute(request); - } - - private HttpResponse sendOpenIdProfilePost(List keyValues) throws IOException { - HttpPost request = new HttpPost(OPEN_ID_PROFILE_URL); - request.setHeader("User-Agent", USER_AGENT); - - List urlParameters = new ArrayList(); - - for (KeyValue keyValue:keyValues){ - urlParameters.add(new BasicNameValuePair(keyValue.getKey(), keyValue.getValue())); - } - - request.setEntity(new UrlEncodedFormEntity(urlParameters)); - - return client.execute(request); - } - - private HttpResponse sendApprovalPost() throws IOException { - HttpPost request = new HttpPost(APPROVAL_URL); - request.setHeader("User-Agent", USER_AGENT); - - boolean approvedAlways = (config.getUserConsent() == OpenIDUtils.UserConsent.APPROVE_ALWAYS); - - List urlParameters = new ArrayList(1); - urlParameters.add(new BasicNameValuePair("hasApprovedAlways", String.valueOf(approvedAlways))); - - request.setEntity(new UrlEncodedFormEntity(urlParameters)); - - return client.execute(request); - } - - private void assertClaims(List keyValues){ - StringBuilder sb = new StringBuilder(); - for (KeyValue keyValue:keyValues){ - if (keyValue.key.equals("claimTag")){ - sb.append(keyValue.getValue()); - sb.append(","); - } - - if (keyValue.key.equals("claimValue")){ - sb.append(keyValue.getValue()); - sb.append(","); - } - } - - String claims = sb.toString(); - Assert.assertTrue(claims.contains(firstNameClaimURI)); - Assert.assertTrue(claims.contains(config.getUser().getUsername())); - Assert.assertTrue(claims.contains(emailClaimURI)); - Assert.assertTrue(claims.contains(config.getUser().getEmail())); - } - - private void assertLogin(String results){ - Assert.assertTrue(results.contains("You are logged in as " + - "https://localhost:9853/openid/" + config.getUser().getUsername()), - "OpenId sso login has failed for " + config); - } - - private void assertAttributes(String results){ - String str = results.substring(results.lastIndexOf("")); - - String[] dataArray = StringUtils.substringsBetween(str, ""); - Map attributeMap = new HashMap(); - String key = null; - String value; - for (int i = 0; i< dataArray.length; i++){ - if((i%2) == 0){ - key = dataArray[i]; - }else{ - value = dataArray[i].trim(); - attributeMap.put(key,value); - } - } - - OpenIDUtils.User user = config.getUser(); - - Assert.assertTrue(attributeMap.containsKey("email"), "Claim email is expected"); - Assert.assertEquals(attributeMap.get("email"), user.getEmail(), - "Expected claim value for email is " + user.getEmail()); - Assert.assertTrue(attributeMap.containsKey("nickname"), "Claim nickname is expected"); - Assert.assertEquals(attributeMap.get("nickname"), user.getUsername(), - "Expected claim value for nickname is " + user.getUsername()); - Assert.assertTrue(attributeMap.containsKey("lastname"), "Claim lastname is expected"); - Assert.assertEquals(attributeMap.get("lastname"), user.getUsername(), - "Expected claim value for lastname is " + user.getUsername()); - } - - private void changeISConfiguration() throws Exception { - log.info("Replacing identity.xml with OpenIDSkipUserConsent property set to true"); - - String carbonHome = Utils.getResidentCarbonHome(); - identityXML = new File(carbonHome + File.separator - + "repository" + File.separator + "conf" + File.separator + "identity" +File.separator + "identity.xml"); - File configuredIdentityXML = new File(getISResourceLocation() - + File.separator + "openId" + File.separator - + "identity-skipuserconsent.xml"); - - serverConfigurationManager = new ServerConfigurationManager(isServer); - serverConfigurationManager.applyConfigurationWithoutRestart(configuredIdentityXML, identityXML, true); - serverConfigurationManager.restartGracefully(); - } - - private void resetISConfiguration() throws Exception{ - log.info("Replacing identity.xml with default configurations"); - - File defaultIdentityXML = new File(getISResourceLocation() + File.separator + "default-identity.xml"); - - serverConfigurationManager.applyConfigurationWithoutRestart(defaultIdentityXML, identityXML, true); - serverConfigurationManager.restartGracefully(); - } - - static class KeyValue{ - private String key; - private String value; - - KeyValue(String key, String value) { - this.key = key; - this.value = value; - } - - public String getValue() { - return value; - } - - public String getKey() { - return key; - } - } -} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/openid/OpenIDUserProfileTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/openid/OpenIDUserProfileTestCase.java deleted file mode 100644 index 2853b1a5b80..00000000000 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/openid/OpenIDUserProfileTestCase.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - *Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - *WSO2 Inc. licenses this file to you under the Apache License, - *Version 2.0 (the "License"); you may not use this file except - *in compliance with the License. - *You may obtain a copy of the License at - * - *http://www.apache.org/licenses/LICENSE-2.0 - * - *Unless required by applicable law or agreed to in writing, - *software distributed under the License is distributed on an - *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - *KIND, either express or implied. See the License for the - *specific language governing permissions and limitations - *under the License. - */ -package org.wso2.identity.integration.test.openid; - -import org.testng.Assert; -import org.testng.annotations.*; -import org.wso2.carbon.identity.provider.openid.stub.dto.OpenIDClaimDTO; -import org.wso2.carbon.identity.provider.openid.stub.dto.OpenIDParameterDTO; -import org.wso2.carbon.identity.provider.openid.stub.dto.OpenIDUserProfileDTO; -import org.wso2.identity.integration.common.clients.openid.OpenIDProviderServiceClient; -import org.wso2.identity.integration.common.clients.usermgt.remote.RemoteUserStoreManagerServiceClient; -import org.wso2.identity.integration.common.utils.ISIntegrationTest; -import org.wso2.carbon.um.ws.api.stub.ClaimValue; - -public class OpenIDUserProfileTestCase extends ISIntegrationTest { - - String userName = "suresh"; - String password = "Wso2@123"; - String[] roles = { "admin" }; - String profileName = "default"; - - // claims - String emailClaimURI = "http://axschema.org/contact/email"; - String emailClaimValue = "suresh@wso2.com"; - String firstNameClaimURI = "http://axschema.org/namePerson/first"; - String firstNameClaimValue = "Suresh"; - String lastNameClaimURI = "http://axschema.org/namePerson/last"; - String lastNameClaimValue = "Attanayake"; - String countryClaimURI = "http://axschema.org/contact/country/home"; - String countryClaimValue = "Sri Lanka"; - - ClaimValue[] claimValues = new ClaimValue[4]; - - private OpenIDProviderServiceClient openidServiceClient; - - @BeforeClass(alwaysRun = true) - public void testInit() throws Exception { - super.init(); - - openidServiceClient = new OpenIDProviderServiceClient(backendURL, sessionCookie); - createUser(); - } - - @AfterClass(alwaysRun = true) - public void atEnd() throws Exception { - super.init(); - deleteUser(); - - openidServiceClient = null; - } - - @Test(alwaysRun = true, description = "Test reading user profile and claims from the profile") - public void testUserProfile() { - - String openId = Util.getDefaultOpenIDIdentifier(userName); - OpenIDParameterDTO[] openidRequestParams = Util.getDummyOpenIDParameterDTOArray(); - - OpenIDUserProfileDTO[] userProfiles = null; - // reading back user profiles - try { - userProfiles = openidServiceClient.getUserProfiles(openId, openidRequestParams); - } catch (Exception e) { - Assert.fail("Error while reading user profiles", e); - } - - Assert.assertEquals(userProfiles[0].getProfileName(), profileName); - Assert.assertNotNull(userProfiles[0].getClaimSet()); - - // we expect 4 claims : email, firstname, lastname and country - Assert.assertEquals(userProfiles[0].getClaimSet().length, 4); - - for (OpenIDClaimDTO claimDTO: userProfiles[0].getClaimSet()){ - if (emailClaimURI.equals(claimDTO.getClaimUri())) { - Assert.assertTrue(claimDTO.getClaimValue().contains(emailClaimValue)); - } else if (firstNameClaimURI.equals(claimDTO.getClaimUri())) { - Assert.assertTrue(claimDTO.getClaimValue().contains(firstNameClaimValue)); - } else if (lastNameClaimURI.equals(claimDTO.getClaimUri())) { - Assert.assertTrue(claimDTO.getClaimValue().contains(lastNameClaimValue)); - } else if (countryClaimURI.equals(claimDTO.getClaimUri())) { - Assert.assertTrue(claimDTO.getClaimValue().contains(countryClaimValue)); - } else { - Assert.fail("Invalid claim returned"); - } - } - - // To access claims for the OpenID user need to have an authenticated session. - // Login with created user - try { - openidServiceClient.authenticateWithOpenID(openId, password); - } catch (Exception e) { - Assert.fail("Error while authenticating", e); - } - } - - @Test(alwaysRun = true, description = "Test OpenID authentication") - public void testOpenIDAuthentication() { - - String openId = Util.getDefaultOpenIDIdentifier(userName); - - boolean isAuthenticated = false; - - try { - isAuthenticated = openidServiceClient.authenticateWithOpenID(openId, password); - } catch (Exception e) { - Assert.fail("Error while authenticating", e); - } - - Assert.assertTrue(isAuthenticated); - } - - @Test(alwaysRun = true, description = "Test reading claims", dependsOnMethods = { "testOpenIDAuthentication" }) - public void testClaims() { - - String openId = Util.getDefaultOpenIDIdentifier(userName); - OpenIDParameterDTO[] openidRequestParams = Util.getDummyOpenIDParameterDTOArray(); - - OpenIDClaimDTO[] claims = null; - try { - // reading back user claims - claims = openidServiceClient.getClaimValues(openId, profileName, openidRequestParams); - } catch (Exception e) { - Assert.fail("Error while reading user claims", e); - } - - // we expect 4 claims : email, firstname, lastname and country - Assert.assertEquals(claims.length, 4); - - // now checking claim values - for (OpenIDClaimDTO dto : claims) { - if (emailClaimURI.equals(dto.getClaimUri())) { - Assert.assertTrue(dto.getClaimValue().contains(emailClaimValue)); - } else if (firstNameClaimURI.equals(dto.getClaimUri())) { - Assert.assertTrue(dto.getClaimValue().contains(firstNameClaimValue)); - } else if (lastNameClaimURI.equals(dto.getClaimUri())) { - Assert.assertTrue(dto.getClaimValue().contains(lastNameClaimValue)); - } else if (countryClaimURI.equals(dto.getClaimUri())) { - Assert.assertTrue(dto.getClaimValue().contains(countryClaimValue)); - } else { - Assert.fail("Invalid claim returned"); - } - } - } - - public void createUser() throws Exception { - ClaimValue email = new ClaimValue(); - email.setClaimURI(emailClaimURI); - email.setValue(emailClaimValue); - claimValues[0] = email; - - ClaimValue firstName = new ClaimValue(); - firstName.setClaimURI(firstNameClaimURI); - firstName.setValue(firstNameClaimValue); - claimValues[1] = firstName; - - ClaimValue lastName = new ClaimValue(); - lastName.setClaimURI(lastNameClaimURI); - lastName.setValue(lastNameClaimValue); - claimValues[2] = lastName; - - ClaimValue country = new ClaimValue(); - country.setClaimURI(countryClaimURI); - country.setValue(countryClaimValue); - claimValues[3] = country; - - // creating the user - RemoteUserStoreManagerServiceClient remoteUSMServiceClient = new RemoteUserStoreManagerServiceClient - (backendURL, sessionCookie); - remoteUSMServiceClient.addUser(userName, password, roles, claimValues, profileName, true); - } - - public void deleteUser() throws Exception { - RemoteUserStoreManagerServiceClient remoteUSMServiceClient = new RemoteUserStoreManagerServiceClient - (backendURL, sessionCookie); - remoteUSMServiceClient.deleteUser(userName); - } -} \ No newline at end of file diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/openid/OpenIDUtils.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/openid/OpenIDUtils.java deleted file mode 100644 index 26518cbcc29..00000000000 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/openid/OpenIDUtils.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.identity.integration.test.openid; - -public class OpenIDUtils { - - public enum User { - ADMIN("openidadmin","Wso2@test", "openidadmin@wso2.com", "admin"), - USER1("openiduser1", "Wso2@test1", "openiduser1@wso2.com", "internal/everyone"), - USER2("openiduser2", "Wso2@test2", "openiduser2@wso2.com", "internal/everyone"); - - private String username; - private String password; - private String email; - private String role; - - User(String username, String password, String email, String role) { - this.username = username; - this.password = password; - this.email = email; - this.role = role; - } - - public String getUsername() { - return username; - } - - public String getPassword() { - return password; - } - - public String getEmail() { - return email; - } - - public String getRole() { - return role; - } - }; - - public enum UserConsent{ - APPROVE, - APPROVE_ALWAYS, - SKIP - }; - - public enum AppType{ - SMART_WITH_CLAIMS("travelocity.com-openid-smartconsumerwithclaims"), - SMART_WITHOUT_CLAIMS("travelocity.com-openid-smartconsumerwithoutclaims"), - DUMB_WITH_CLAIMS("travelocity.com-openid-dumbconsumerwithclaims"), - DUMB_WITHOUT_CLAIMS("travelocity.com-openid-dumbconsumerwithoutclaims"); - - private String artifact; - - AppType(String artifact) { - this.artifact = artifact; - } - - public String getArtifact() { - return artifact; - } - } - - public static class OpenIDConfig { - - private User user; - private UserConsent userConsent; - private AppType appType; - - - public OpenIDConfig(User user, UserConsent userConsent, AppType appType) { - this.user = user; - this.userConsent = userConsent; - this.appType = appType; - } - - public User getUser() { - return user; - } - - public UserConsent getUserConsent() { - return userConsent; - } - - public AppType getAppType() { - return appType; - } - - @Override - public String toString() { - return "OpenIdConfig[" + - "user=" + user + - ", userConsent=" + userConsent + - ", appType=" + appType + - ']'; - } - } - -} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/openid/Util.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/openid/Util.java deleted file mode 100644 index 7968426da87..00000000000 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/openid/Util.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.wso2.identity.integration.test.openid; - - -import org.wso2.carbon.identity.provider.openid.stub.dto.OpenIDParameterDTO; - -public class Util { - - public static String openidUserIDBase = "https://localhost:9853/openid/"; - - /** - * Return the OpenID Identifier of the username - * - * @param username - * @return - */ - public static String getDefaultOpenIDIdentifier(String username) { - return openidUserIDBase.concat(username); - } - - /** - * Returns a dummy request with four claims requests : firstname, lastname, - * country and email. - * - * @return - */ - public static OpenIDParameterDTO[] getDummyOpenIDParameterDTOArray() { - - OpenIDParameterDTO[] openidParams = new OpenIDParameterDTO[14]; - - OpenIDParameterDTO ext1 = new OpenIDParameterDTO(); - ext1.setName("openid.ns.ext1"); - ext1.setValue("http://openid.net/srv/ax/1.0"); - openidParams[0] = ext1; - - OpenIDParameterDTO claimedID = new OpenIDParameterDTO(); - claimedID.setName("openid.claimed_id"); - claimedID.setValue("https://localhost:9853/openid/suresh"); - openidParams[1] = claimedID; - - OpenIDParameterDTO required = new OpenIDParameterDTO(); - required.setName("openid.ext1.required"); - required.setValue("email,firstname,lastname,country"); - openidParams[2] = required; - - OpenIDParameterDTO handle = new OpenIDParameterDTO(); - handle.setName("openid.assoc_handle"); - handle.setValue("32471379494934315-1"); - openidParams[3] = handle; - - OpenIDParameterDTO lastname = new OpenIDParameterDTO(); - lastname.setName("openid.ext1.type.lastname"); - lastname.setValue("http://axschema.org/namePerson/last"); - openidParams[4] = lastname; - - OpenIDParameterDTO ns = new OpenIDParameterDTO(); - ns.setName("openid.ns"); - ns.setValue("http://specs.openid.net/auth/2.0"); - openidParams[5] = ns; - - OpenIDParameterDTO firstname = new OpenIDParameterDTO(); - firstname.setName("openid.ext1.type.firstname"); - firstname.setValue("http://axschema.org/namePerson/first"); - openidParams[6] = firstname; - - OpenIDParameterDTO identity = new OpenIDParameterDTO(); - identity.setName("openid.identity"); - identity.setValue("https://localhost:9853/openid/suresh"); - openidParams[7] = identity; - - OpenIDParameterDTO email = new OpenIDParameterDTO(); - email.setName("openid.ext1.type.email"); - email.setValue("http://axschema.org/contact/email"); - openidParams[8] = email; - - OpenIDParameterDTO mode = new OpenIDParameterDTO(); - mode.setName("openid.mode"); - mode.setValue("checkid_setup"); - openidParams[9] = mode; - - OpenIDParameterDTO extMode = new OpenIDParameterDTO(); - extMode.setName("openid.ext1.mode"); - extMode.setValue("fetch_request"); - openidParams[10] = extMode; - - OpenIDParameterDTO realm = new OpenIDParameterDTO(); - realm.setName("openid.realm"); - realm.setValue("http://localhost:8490/openid-client"); - openidParams[11] = realm; - - OpenIDParameterDTO country = new OpenIDParameterDTO(); - country.setName("openid.ext1.type.country"); - country.setValue("http://axschema.org/contact/country/home"); - openidParams[12] = country; - - OpenIDParameterDTO returnto = new OpenIDParameterDTO(); - returnto.setName("openid.return_to"); - returnto.setValue("http://localhost:8490/openid-client/"); - openidParams[13] = returnto; - - return openidParams; - - } - -} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/recovery/PasswordRecoveryTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/recovery/PasswordRecoveryTestCase.java index cc6f9981325..c699c6006bd 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/recovery/PasswordRecoveryTestCase.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/recovery/PasswordRecoveryTestCase.java @@ -43,6 +43,7 @@ import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; +import org.wso2.identity.integration.test.base.MockApplicationServer; import org.wso2.identity.integration.test.oidc.OIDCAbstractIntegrationTest; import org.wso2.identity.integration.test.oidc.OIDCUtilTest; import org.wso2.identity.integration.test.oidc.bean.OIDCApplication; @@ -60,6 +61,8 @@ import java.util.ArrayList; import java.util.List; +import static org.wso2.identity.integration.test.utils.OAuth2Constant.AUTHORIZE_ENDPOINT_URL; + /** * Test password recovery functionality. */ @@ -72,6 +75,7 @@ public class PasswordRecoveryTestCase extends OIDCAbstractIntegrationTest { private CloseableHttpClient client; private OIDCApplication oidcApplication; private UserObject userObject; + private MockApplicationServer mockApplicationServer; public static final String USERNAME = "recoverytestuser"; public static final String PASSWORD = "Oidcsessiontestuser@123"; @@ -103,6 +107,9 @@ public void testInit() throws Exception { userObject = initUser(); createUser(userObject); + + mockApplicationServer = new MockApplicationServer(); + mockApplicationServer.start(); } @AfterClass(alwaysRun = true) @@ -114,6 +121,7 @@ public void testClear() throws Exception { identityGovernanceRestClient.closeHttpClient(); client.close(); Utils.getMailServer().purgeEmailFromAllMailboxes(); + mockApplicationServer.stop(); } @Test @@ -129,12 +137,13 @@ public void testPasswordRecovery() throws Exception { private String retrievePasswordResetURL(OIDCApplication application, HttpClient client) throws Exception { - List urlParameters = OIDCUtilTest.getNameValuePairs(application, - getTenantQualifiedURL(OAuth2Constant.APPROVAL_URL, tenantInfo.getDomain())); - - HttpResponse response = sendPostRequestWithParameters(client, urlParameters, String.format - (OIDCUtilTest.targetApplicationUrl, application.getApplicationContext() + OAuth2Constant.PlaygroundAppPaths - .appUserAuthorizePath)); + List urlParameters = new ArrayList<>(); + urlParameters.add(new BasicNameValuePair("response_type", OAuth2Constant.OAUTH2_GRANT_TYPE_CODE)); + urlParameters.add(new BasicNameValuePair("client_id", application.getClientId())); + urlParameters.add(new BasicNameValuePair("redirect_uri", application.getCallBackURL())); + urlParameters.add(new BasicNameValuePair("scope", "openid email profile")); + HttpResponse response = sendPostRequestWithParameters(client, urlParameters, + getTenantQualifiedURL(AUTHORIZE_ENDPOINT_URL, tenantInfo.getDomain())); Header authorizeRequestURL = response.getFirstHeader(OAuth2Constant.HTTP_RESPONSE_HEADER_LOCATION); EntityUtils.consume(response.getEntity()); @@ -192,7 +201,6 @@ private void updatePasswordRecoveryFeatureStatus(boolean enable) throws IOExcept private OIDCApplication initApplication() { OIDCApplication playgroundApp = new OIDCApplication(OIDCUtilTest.playgroundAppOneAppName, - OIDCUtilTest.playgroundAppOneAppContext, OIDCUtilTest.playgroundAppOneAppCallBackUri); playgroundApp.addRequiredClaim(OIDCUtilTest.emailClaimUri); playgroundApp.addRequiredClaim(OIDCUtilTest.firstNameClaimUri); diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/common/RESTTestBase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/common/RESTTestBase.java index a8f0478e679..e6ffcb5ff89 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/common/RESTTestBase.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/common/RESTTestBase.java @@ -380,6 +380,27 @@ protected Response getResponseOfPost(String endpointUri, String body) { .post(endpointUri); } + /** + * Invoke given endpointUri for POST with given body and Basic authentication, authentication credential being the + * authenticatingUserName and authenticatingCredential. + * This implementation does not incorporate any additional filters. + * + * @param endpointUri endpoint to be invoked + * @param body payload + * @return response + */ + protected Response getResponseOfPostNoFilter(String endpointUri, String body) { + + return given().auth().preemptive().basic(authenticatingUserName, authenticatingCredential) + .contentType(ContentType.JSON) + .header(HttpHeaders.ACCEPT, ContentType.JSON) + .body(body) + .log().ifValidationFails() + .when() + .log().ifValidationFails() + .post(endpointUri); + } + /** * Invoke given endpointUri for POST with given body and Basic authentication, authentication credential being the * authenticatingUserName and authenticatingCredential diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/action/management/v1/ActionsFailureTest.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/action/management/v1/ActionsFailureTest.java index bb705ee0fda..ba3094badae 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/action/management/v1/ActionsFailureTest.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/action/management/v1/ActionsFailureTest.java @@ -32,7 +32,6 @@ import org.wso2.identity.integration.test.rest.api.server.action.management.v1.model.ActionModel; import org.wso2.identity.integration.test.rest.api.server.action.management.v1.model.ActionUpdateModel; import org.wso2.identity.integration.test.rest.api.server.action.management.v1.model.AuthenticationType; -import org.wso2.identity.integration.test.rest.api.server.action.management.v1.model.AuthenticationTypeProperties; import org.wso2.identity.integration.test.rest.api.server.action.management.v1.model.Endpoint; import java.io.IOException; @@ -159,6 +158,18 @@ public void testCreateActionAfterReachingMaxActionCount() { } @Test(dependsOnMethods = {"testCreateActionAfterReachingMaxActionCount"}) + public void testGetActionByActionIdWithInvalidID() { + + Response responseOfGet = getResponseOfGet(ACTION_MANAGEMENT_API_BASE_PATH + + PRE_ISSUE_ACCESS_TOKEN_PATH + "/" + TEST_ACTION_INVALID_ID); + + responseOfGet.then() + .log().ifValidationFails() + .assertThat().statusCode(HttpStatus.SC_NOT_FOUND) + .body("description", equalTo("No action is found for given action id and action type")); + } + + @Test(dependsOnMethods = {"testGetActionByActionIdWithInvalidID"}) public void testCreateActionWithNotImplementedActionTypes() { for (String actionTypePath : NOT_IMPLEMENTED_ACTION_TYPE_PATHS) { @@ -187,60 +198,9 @@ public void testUpdateActionWithInvalidID() { .log().ifValidationFails() .assertThat().statusCode(HttpStatus.SC_NOT_FOUND) .body("description", equalTo("No Action is configured on the given Action Type and Id.")); - - // Update Action Endpoint Authentication Properties with an invalid action id. - AuthenticationTypeProperties authenticationType = new AuthenticationTypeProperties() - .properties(new HashMap() {{ - put(TEST_ACCESS_TOKEN_AUTH_PROPERTY, TEST_ACCESS_TOKEN_AUTH_PROPERTY_VALUE); - }}); - - body = toJSONString(authenticationType); - Response responseOfPut = getResponseOfPut(ACTION_MANAGEMENT_API_BASE_PATH + - PRE_ISSUE_ACCESS_TOKEN_PATH + "/" + TEST_ACTION_INVALID_ID + ACTION_BEARER_AUTH_PATH, body); - responseOfPut.then() - .log().ifValidationFails() - .assertThat().statusCode(HttpStatus.SC_NOT_FOUND) - .body("description", equalTo("No Action is configured on the given Action Type and Id.")); } @Test(dependsOnMethods = {"testUpdateActionWithInvalidID"}) - public void testUpdateActionWithInvalidEndpointAuthProperties() { - - AuthenticationTypeProperties authenticationType = new AuthenticationTypeProperties() - .properties(new HashMap() {{ - put(TEST_USERNAME_INVALID_AUTH_PROPERTY, TEST_USERNAME_AUTH_PROPERTY_VALUE); - put(TEST_PASSWORD_AUTH_PROPERTY, TEST_PASSWORD_AUTH_PROPERTY_VALUE); - }}); - - String body = toJSONString(authenticationType); - Response responseOfPut = getResponseOfPut(ACTION_MANAGEMENT_API_BASE_PATH + - PRE_ISSUE_ACCESS_TOKEN_PATH + "/" + testActionId2 + ACTION_BASIC_AUTH_PATH, body); - responseOfPut.then() - .log().ifValidationFails() - .assertThat().statusCode(HttpStatus.SC_BAD_REQUEST) - .body("description", equalTo("Required authentication properties are not " + - "provided or invalid.")); - } - - @Test(dependsOnMethods = {"testUpdateActionWithInvalidEndpointAuthProperties"}) - public void testUpdateActionWithEmptyEndpointAuthPropertyValues() { - - AuthenticationTypeProperties authenticationType = new AuthenticationTypeProperties() - .properties(new HashMap() {{ - put(TEST_USERNAME_AUTH_PROPERTY, ""); - put(TEST_PASSWORD_AUTH_PROPERTY, TEST_PASSWORD_AUTH_PROPERTY_VALUE); - }}); - - String body = toJSONString(authenticationType); - Response responseOfPut = getResponseOfPut(ACTION_MANAGEMENT_API_BASE_PATH + - PRE_ISSUE_ACCESS_TOKEN_PATH + "/" + testActionId2 + ACTION_BASIC_AUTH_PATH, body); - responseOfPut.then() - .log().ifValidationFails() - .assertThat().statusCode(HttpStatus.SC_BAD_REQUEST) - .body("description", equalTo("Authentication property values cannot be empty.")); - } - - @Test(dependsOnMethods = {"testUpdateActionWithEmptyEndpointAuthPropertyValues"}) public void testActivateActionWithInvalidID() { getResponseOfPost(ACTION_MANAGEMENT_API_BASE_PATH + PRE_ISSUE_ACCESS_TOKEN_PATH + diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/action/management/v1/ActionsSuccessTest.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/action/management/v1/ActionsSuccessTest.java index 7e7494bb729..6211f02cd37 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/action/management/v1/ActionsSuccessTest.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/action/management/v1/ActionsSuccessTest.java @@ -30,7 +30,6 @@ import org.wso2.identity.integration.test.rest.api.server.action.management.v1.model.ActionModel; import org.wso2.identity.integration.test.rest.api.server.action.management.v1.model.ActionUpdateModel; import org.wso2.identity.integration.test.rest.api.server.action.management.v1.model.AuthenticationType; -import org.wso2.identity.integration.test.rest.api.server.action.management.v1.model.AuthenticationTypeProperties; import org.wso2.identity.integration.test.rest.api.server.action.management.v1.model.Endpoint; import org.wso2.identity.integration.test.rest.api.server.action.management.v1.model.EndpointUpdateModel; @@ -113,7 +112,7 @@ public void testCreateAction() { } @Test(dependsOnMethods = {"testCreateAction"}) - public void testGetActionByActionType() { + public void testGetActionsByActionType() { Response responseOfGet = getResponseOfGet(ACTION_MANAGEMENT_API_BASE_PATH + PRE_ISSUE_ACCESS_TOKEN_PATH); @@ -124,14 +123,33 @@ public void testGetActionByActionType() { .body( "find { it.id == '" + testActionId + "' }.name", equalTo(TEST_ACTION_NAME)) .body( "find { it.id == '" + testActionId + "' }.description", equalTo(TEST_ACTION_DESCRIPTION)) .body( "find { it.id == '" + testActionId + "' }.status", equalTo(TEST_ACTION_ACTIVE_STATUS)) - .body( "find { it.id == '" + testActionId + "' }.endpoint.uri", equalTo(TEST_ENDPOINT_URI)) - .body( "find { it.id == '" + testActionId + "' }.endpoint.authentication.type", - equalTo(AuthenticationType.TypeEnum.BASIC.toString())) - .body( "find { it.id == '" + testActionId + "' }.endpoint.authentication", - not(hasKey(TEST_PROPERTIES_AUTH_ATTRIBUTE))); + .body("find { it.id == '" + testActionId + "' }.links", notNullValue()) + .body("find { it.id == '" + testActionId + "' }.links.find { it.rel == 'self' }.href", + equalTo(buildBaseURL() + ACTION_MANAGEMENT_API_BASE_PATH + + PRE_ISSUE_ACCESS_TOKEN_PATH + "/" + testActionId)) + .body("find { it.id == '" + testActionId + "' }.links.find { it.rel == 'self' }.method", + equalTo("GET")); } - @Test(dependsOnMethods = {"testGetActionByActionType"}) + @Test(dependsOnMethods = {"testGetActionsByActionType"}) + public void testGetActionByActionId() { + + Response responseOfGet = getResponseOfGet(ACTION_MANAGEMENT_API_BASE_PATH + + PRE_ISSUE_ACCESS_TOKEN_PATH + "/" + testActionId); + responseOfGet.then() + .log().ifValidationFails() + .assertThat() + .statusCode(HttpStatus.SC_OK) + .body("id", equalTo(testActionId)) + .body("name", equalTo(TEST_ACTION_NAME)) + .body("description", equalTo(TEST_ACTION_DESCRIPTION)) + .body("status", equalTo(TEST_ACTION_ACTIVE_STATUS)) + .body("endpoint.uri", equalTo(TEST_ENDPOINT_URI)) + .body("endpoint.authentication.type", equalTo(AuthenticationType.TypeEnum.BASIC.toString())) + .body("endpoint.authentication", not(hasKey(TEST_PROPERTIES_AUTH_ATTRIBUTE))); + } + + @Test(dependsOnMethods = {"testGetActionByActionId"}) public void testGetActionTypes() { Response responseOfGet = getResponseOfGet(ACTION_MANAGEMENT_API_BASE_PATH + TYPES_API_PATH); @@ -324,45 +342,6 @@ public void testUpdateAction() { } @Test(dependsOnMethods = {"testUpdateAction"}) - public void testUpdateEndpointAuthentication() { - - AuthenticationTypeProperties newAuthProperties = new AuthenticationTypeProperties() - .properties(new HashMap() {{ - put(TEST_ACCESS_TOKEN_AUTH_PROPERTY, TEST_ACCESS_TOKEN_AUTH_PROPERTY_VALUE); - }}); - - String body = toJSONString(newAuthProperties); - Response responseOfPut = getResponseOfPut(ACTION_MANAGEMENT_API_BASE_PATH + - PRE_ISSUE_ACCESS_TOKEN_PATH + "/" + testActionId + ACTION_BEARER_AUTH_PATH, body); - - responseOfPut.then() - .log().ifValidationFails() - .assertThat() - .statusCode(HttpStatus.SC_OK) - .body("endpoint.uri", equalTo(TEST_ENDPOINT_URI)) - .body("endpoint.authentication.type", equalTo(AuthenticationType.TypeEnum.BEARER.toString())); - } - - @Test(dependsOnMethods = {"testUpdateEndpointAuthentication"}) - public void testUpdateEndpointAuthProperties() { - - AuthenticationTypeProperties newAuthProperties = new AuthenticationTypeProperties() - .properties(new HashMap() {{ - put(TEST_ACCESS_TOKEN_AUTH_PROPERTY, TEST_UPDATED_ACCESS_TOKEN_AUTH_PROPERTY_VALUE); - }}); - - String body = toJSONString(newAuthProperties); - Response responseOfPut = getResponseOfPut(ACTION_MANAGEMENT_API_BASE_PATH + - PRE_ISSUE_ACCESS_TOKEN_PATH + "/" + testActionId + ACTION_BEARER_AUTH_PATH, body); - - responseOfPut.then() - .log().ifValidationFails() - .assertThat() - .statusCode(HttpStatus.SC_OK) - .body("endpoint.authentication.type", equalTo(AuthenticationType.TypeEnum.BEARER.toString())); - } - - @Test(dependsOnMethods = {"testUpdateEndpointAuthProperties"}) public void testDeactivateAction() { getResponseOfPost(ACTION_MANAGEMENT_API_BASE_PATH + PRE_ISSUE_ACCESS_TOKEN_PATH + @@ -434,29 +413,7 @@ public void testCreateActionWithExtraEndpointAuthProperties() { .statusCode(HttpStatus.SC_CREATED) .body("endpoint.authentication.type", equalTo(AuthenticationType.TypeEnum.BASIC.toString())); - testActionId = responseOfPost.getBody().jsonPath().getString("id"); - } - - @Test(dependsOnMethods = {"testCreateActionWithExtraEndpointAuthProperties"}) - public void testUpdateActionWithExtraEndpointAuthProperties() { - - AuthenticationTypeProperties newAuthProperties = new AuthenticationTypeProperties() - .properties(new HashMap() {{ - put(TEST_ACCESS_TOKEN_AUTH_PROPERTY, TEST_ACCESS_TOKEN_AUTH_PROPERTY_VALUE); - put(TEST_USERNAME_AUTH_PROPERTY, TEST_USERNAME_AUTH_PROPERTY_VALUE); - }}); - - String body = toJSONString(newAuthProperties); - Response responseOfPut = getResponseOfPut(ACTION_MANAGEMENT_API_BASE_PATH + - PRE_ISSUE_ACCESS_TOKEN_PATH + "/" + testActionId + ACTION_BEARER_AUTH_PATH, body); - - responseOfPut.then() - .log().ifValidationFails() - .assertThat() - .statusCode(HttpStatus.SC_OK) - .body("endpoint.authentication.type", equalTo(AuthenticationType.TypeEnum.BEARER.toString())); - // Delete, created action. - deleteAction(PRE_ISSUE_ACCESS_TOKEN_PATH , testActionId); + deleteAction(PRE_ISSUE_ACCESS_TOKEN_PATH , responseOfPost.getBody().jsonPath().getString("id")); } } diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/action/management/v1/ActionsTestBase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/action/management/v1/ActionsTestBase.java index 0770b8ae09f..3832d2f4a75 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/action/management/v1/ActionsTestBase.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/action/management/v1/ActionsTestBase.java @@ -28,6 +28,7 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.wso2.carbon.automation.engine.context.TestUserMode; +import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import org.wso2.identity.integration.test.rest.api.server.common.RESTAPIServerTestBase; import java.io.IOException; @@ -44,8 +45,6 @@ public class ActionsTestBase extends RESTAPIServerTestBase { protected static final String PRE_ISSUE_ACCESS_TOKEN_PATH = "/preIssueAccessToken"; protected static final String ACTION_DEACTIVATE_PATH = "/deactivate"; protected static final String ACTION_ACTIVATE_PATH = "/activate"; - protected static final String ACTION_BEARER_AUTH_PATH = "/bearer"; - protected static final String ACTION_BASIC_AUTH_PATH = "/basic"; protected static final String PRE_ISSUE_ACCESS_TOKEN_ACTION_TYPE = "PRE_ISSUE_ACCESS_TOKEN"; @@ -140,5 +139,19 @@ protected String toJSONString(Object object) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); return gson.toJson(object); } + + /** + * Build the base URL for the REST API. + * + * @return Base URL. + */ + public String buildBaseURL() { + + if (this.tenant.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { + return String.format(API_SERVER_BASE_PATH, "v1"); + } else { + return "/t/" + this.tenant + String.format(API_SERVER_BASE_PATH, "v1"); + } + } } diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/application/management/v1/ApplicationManagementPassiveStsSuccessTest.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/application/management/v1/ApplicationManagementPassiveStsSuccessTest.java index 5cbd405e7ef..5c394a1fbfc 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/application/management/v1/ApplicationManagementPassiveStsSuccessTest.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/application/management/v1/ApplicationManagementPassiveStsSuccessTest.java @@ -23,7 +23,6 @@ import org.testng.annotations.Factory; import org.testng.annotations.Test; import org.wso2.carbon.automation.engine.context.TestUserMode; -import org.wso2.identity.integration.test.openid.Util; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.Matchers.notNullValue; diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/branding/preference/management/v1/AppBrandingPreferenceManagementSuccessTest.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/branding/preference/management/v1/AppBrandingPreferenceManagementSuccessTest.java index 4669440bf54..cdc35322f17 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/branding/preference/management/v1/AppBrandingPreferenceManagementSuccessTest.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/branding/preference/management/v1/AppBrandingPreferenceManagementSuccessTest.java @@ -41,7 +41,7 @@ import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.core.IsNull.notNullValue; import static org.testng.Assert.assertNotNull; -import static org.wso2.identity.integration.test.entitlement.EntitlementJSONSupportMultiDecisionProfileTestCase.areJSONObjectsEqual; +import static org.wso2.identity.integration.test.util.Utils.areJSONObjectsEqual; /** * Tests for happy paths of the managing application branding using Branding Preference Management REST API. diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/branding/preference/management/v1/BrandingPreferenceManagementSuccessTest.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/branding/preference/management/v1/BrandingPreferenceManagementSuccessTest.java index 8180a6c301b..e39eb541148 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/branding/preference/management/v1/BrandingPreferenceManagementSuccessTest.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/branding/preference/management/v1/BrandingPreferenceManagementSuccessTest.java @@ -36,11 +36,11 @@ import org.wso2.carbon.automation.engine.context.TestUserMode; import java.io.IOException; +import static org.wso2.identity.integration.test.util.Utils.areJSONObjectsEqual; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.core.IsNull.notNullValue; import static org.testng.Assert.assertNotNull; -import static org.wso2.identity.integration.test.entitlement.EntitlementJSONSupportMultiDecisionProfileTestCase.areJSONObjectsEqual; /** * Test class for Branding Preference Management REST APIs success paths. diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/claim/management/v1/ClaimManagementNegativeTest.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/claim/management/v1/ClaimManagementNegativeTest.java index dfb5051daa0..da8019b7815 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/claim/management/v1/ClaimManagementNegativeTest.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/claim/management/v1/ClaimManagementNegativeTest.java @@ -18,7 +18,6 @@ import io.restassured.RestAssured; import io.restassured.response.Response; -import org.apache.axis2.AxisFault; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpHeaders; import org.apache.http.HttpStatus; @@ -43,8 +42,8 @@ */ public class ClaimManagementNegativeTest extends ClaimManagementTestBase { - private static String testDialectId = "aHR0cDovL3VwZGF0ZWRkdW1teS5vcmcvY6xhaW0"; - private static String testClaimId = "aHR0cDovL2ludmFsaWRkdW1teS5vcmcvY2xhaW0vZW1haWxhZGRyZXNz"; + private static final String testDialectId = "aHR0cDovL3VwZGF0ZWRkdW1teS5vcmcvY6xhaW0"; + private static final String testClaimId = "aHR0cDovL2ludmFsaWRkdW1teS5vcmcvY2xhaW0vZW1haWxhZGRyZXNz"; @Factory(dataProvider = "restAPIUserConfigProvider") public ClaimManagementNegativeTest(TestUserMode userMode) throws Exception { @@ -96,6 +95,135 @@ public void testGetDialectWithInvalidDialectId() { validateErrorResponse(response, HttpStatus.SC_NOT_FOUND, "CMT-50016", testDialectId); } + @Test + public void testRemoveSystemDefaultDialect() { + + String dialectId = "local"; + removeDialect(dialectId); + getResponseOfGet(CLAIM_DIALECTS_ENDPOINT_URI + "/" + dialectId) + .then() + .log().ifValidationFails() + .assertThat() + .statusCode(HttpStatus.SC_OK) + .body("id", equalTo(dialectId)) + .body("dialectURI", equalTo("http://wso2.org/claims")); + + dialectId = "dXJuOmlldGY6cGFyYW1zOnNjaW06c2NoZW1hczpjb3JlOjIuMA"; + getResponseOfDelete(CLAIM_DIALECTS_ENDPOINT_URI + "/" + dialectId) + .then() + .log().ifValidationFails() + .assertThat() + .statusCode(HttpStatus.SC_FORBIDDEN) + .body("code", equalTo("CMT-60008")); + } + + @Test + public void testAddExistingDialect() throws IOException { + + String dialectId = createDialect(); + + String body = readResource("claim-management-add-dialect.json"); + Response response = getResponseOfPost(CLAIM_DIALECTS_ENDPOINT_URI, body); + response.then() + .log().ifValidationFails() + .assertThat() + .statusCode(HttpStatus.SC_CONFLICT) + .body("code", equalTo("CMT-60002")); + + removeDialect(dialectId); + } + + @Test + public void testUpdateDefaultDialectURI() throws IOException { + + String dialectId = "aHR0cDovL3dzbzIub3JnL29pZGMvY2xhaW0"; + String body = readResource("claim-management-update-dialect.json"); + Response response = getResponseOfPut(CLAIM_DIALECTS_ENDPOINT_URI + "/" + dialectId, body); + response.then() + .log().ifValidationFails() + .assertThat() + .statusCode(HttpStatus.SC_FORBIDDEN) + .body("code", equalTo("CMT-60007")); + } + + @Test + public void testGetLocalClaimsWithInvalidClaimId() { + + Response response = + getResponseOfGet(CLAIM_DIALECTS_ENDPOINT_URI + LOCAL_CLAIMS_ENDPOINT_URI + "/" + testClaimId); + validateErrorResponse(response, HttpStatus.SC_NOT_FOUND, "CMT-50019", testClaimId); + } + + @Test + public void testUpdateExistingLocalClaimUri() throws IOException { + + String localClaimUri = "http://wso2.org/claims/dummyemailaddress"; + String claimId = createLocalClaim(); + + String body = readResource("claim-management-update-local-claim-conflict.json"); + Response response = getResponseOfPut(CLAIM_DIALECTS_ENDPOINT_URI + LOCAL_CLAIMS_ENDPOINT_URI + "/" + claimId, + body); + validateErrorResponse(response, HttpStatus.SC_CONFLICT, "CMT-50021", localClaimUri); + + removeLocalClaim(claimId); + } + + @Test + public void testAddLocalClaimWithInvalidUsertore() throws IOException { + + String userstore = "DUMMY"; + String body = readResource("claim-management-add-local-claim-invalid-userstore.json"); + Response response = getResponseOfPost(CLAIM_DIALECTS_ENDPOINT_URI + LOCAL_CLAIMS_ENDPOINT_URI, body); + validateErrorResponse(response, HttpStatus.SC_BAD_REQUEST, "CMT-50026", userstore); + } + + @Test + public void testRemoveLocalClaimWithExternalClaimAssociation() throws IOException { + + String localClaimId = createLocalClaim(); + String dialectId = createDialect(); + String claimId = createExternalClaimMappedToCustomLocalClaim(dialectId); + + Response response = getResponseOfDelete(CLAIM_DIALECTS_ENDPOINT_URI + LOCAL_CLAIMS_ENDPOINT_URI + "/" + + localClaimId); + validateErrorResponse(response, HttpStatus.SC_BAD_REQUEST, "CMT-50031"); + + removeExternalClaim(dialectId, claimId); + removeDialect(dialectId); + removeLocalClaim(localClaimId); + } + + @Test + public void testRemoveDefaultLocalClaim() throws IOException { + + String dialectId = "dXJuOmlldGY6cGFyYW1zOnNjaW06c2NoZW1hczpjb3JlOjIuMA"; + String claimId = "dXJuOmlldGY6cGFyYW1zOnNjaW06c2NoZW1hczpjb3JlOjIuMDptZXRhLnJlc291cmNlVHlwZQ=="; + + String body = readResource("claim-management-update-default-external-claim.json"); + Response response = getResponseOfPut(CLAIM_DIALECTS_ENDPOINT_URI + "/" + dialectId + CLAIMS_ENDPOINT_URI + + "/" + claimId, body); + response.then() + .assertThat() + .statusCode(HttpStatus.SC_OK); + + String defaultLocalClaimId = "aHR0cDovL3dzbzIub3JnL2NsYWltcy9yZXNvdXJjZVR5cGU="; + + response = getResponseOfDelete(CLAIM_DIALECTS_ENDPOINT_URI + LOCAL_CLAIMS_ENDPOINT_URI + + "/" + defaultLocalClaimId); + validateErrorResponse(response, HttpStatus.SC_FORBIDDEN, "CMT-60006"); + } + + @Test + public void testAddLocalClaimWithExistingURI() throws IOException { + + String body = readResource("claim-management-add-local-claim-with-existing-uri.json"); + Response response = getResponseOfPost(CLAIM_DIALECTS_ENDPOINT_URI + LOCAL_CLAIMS_ENDPOINT_URI, body); + response.then() + .log().ifValidationFails() + .assertThat() + .statusCode(HttpStatus.SC_CONFLICT); + } + @Test public void testGetClaimsWithInvalidDialectId() { @@ -122,7 +250,7 @@ public void testGetExternalClaimsWhenEmpty() throws IOException { public void testGetExternalClaimsWithInvalidClaimId() throws IOException { String dialectId = createDialect(); - String claimId = createExternalClaim(dialectId); + String claimId = createExternalClaimMappedToDefaultLocalClaim(dialectId); Response response = getResponseOfGet(CLAIM_DIALECTS_ENDPOINT_URI + "/" + dialectId + CLAIMS_ENDPOINT_URI + "/" + testClaimId); @@ -132,20 +260,12 @@ public void testGetExternalClaimsWithInvalidClaimId() throws IOException { removeDialect(dialectId); } - @Test - public void testGetLocalClaimsWithInvalidClaimId() { - - Response response = - getResponseOfGet(CLAIM_DIALECTS_ENDPOINT_URI + LOCAL_CLAIMS_ENDPOINT_URI + "/" + testClaimId); - validateErrorResponse(response, HttpStatus.SC_NOT_FOUND, "CMT-50019", testClaimId); - } - @Test public void testUpdateExistingExternalClaimUri() throws IOException { String externalClaimUri = "http://updateddummy.org/claim/emailaddress"; String dialectId = createDialect(); - String claimId = createExternalClaim(dialectId); + String claimId = createExternalClaimMappedToDefaultLocalClaim(dialectId); String body = readResource("claim-management-update-external-claim-conflict.json"); Response response = getResponseOfPut(CLAIM_DIALECTS_ENDPOINT_URI + "/" + dialectId + CLAIMS_ENDPOINT_URI + @@ -157,17 +277,63 @@ public void testUpdateExistingExternalClaimUri() throws IOException { } @Test - public void testUpdateExistingLocalClaimUri() throws IOException { + public void testAddExternalClaimWithInvalidDialect() throws IOException { - String localClaimUri = "http://wso2.org/claims/dummyemailaddress"; - String claimId = createLocalClaim(); + String body = readResource("claim-management-add-external-claim.json"); + Response response = getResponseOfPost(CLAIM_DIALECTS_ENDPOINT_URI + "/" + testDialectId + CLAIMS_ENDPOINT_URI + , body); + validateErrorResponse(response, HttpStatus.SC_NOT_FOUND, "CMT-50027", testDialectId); + } - String body = readResource("claim-management-update-local-claim-conflict.json"); - Response response = getResponseOfPut(CLAIM_DIALECTS_ENDPOINT_URI + LOCAL_CLAIMS_ENDPOINT_URI + "/" + claimId, + @Test + public void testAddExternalClaimWithInvalidMappedClaim() throws IOException { + + String dialectId = createDialect(); + + String body = readResource("claim-management-add-external-claim-invalid-mapped-claim.json"); + Response response = getResponseOfPost(CLAIM_DIALECTS_ENDPOINT_URI + "/" + dialectId + CLAIMS_ENDPOINT_URI, body); - validateErrorResponse(response, HttpStatus.SC_CONFLICT, "CMT-50021", localClaimUri); + validateErrorResponse(response, HttpStatus.SC_BAD_REQUEST, "CMT-50036"); - removeLocalClaim(claimId); + removeDialect(dialectId); + } + + @Test + public void testAddExternalClaimWithExistingClaimURI() throws IOException { + + String dialectId = createDialect(); + String claimId = createExternalClaimMappedToDefaultLocalClaim(dialectId); + + String body = readResource("claim-management-add-external-claim.json"); + Response response = getResponseOfPost(CLAIM_DIALECTS_ENDPOINT_URI + "/" + dialectId + + CLAIMS_ENDPOINT_URI, body); + response.then() + .log().ifValidationFails() + .assertThat() + .statusCode(HttpStatus.SC_CONFLICT) + .body("code", equalTo("CMT-50038")); + + removeExternalClaim(dialectId, claimId); + removeDialect(dialectId); + } + + @Test + public void testAddExternalClaimWithAlreadyMappedLocalClaim() throws IOException { + + String dialectId = createDialect(); + String claimId = createExternalClaimMappedToDefaultLocalClaim(dialectId); + + String body = readResource("claim-management-add-external-claim-already-mapped.json"); + Response response = getResponseOfPost(CLAIM_DIALECTS_ENDPOINT_URI + "/" + dialectId + + CLAIMS_ENDPOINT_URI, body); + response.then() + .log().ifValidationFails() + .assertThat() + .statusCode(HttpStatus.SC_BAD_REQUEST) + .body("code", equalTo("CMT-60004")); + + removeExternalClaim(dialectId, claimId); + removeDialect(dialectId); } @Test @@ -208,52 +374,6 @@ public void testAttributeFilteringNotImplemented() { validateErrorResponse(response, HttpStatus.SC_NOT_IMPLEMENTED, "CMT-50025"); } - @Test - public void testAddLocalClaimWithInvalidUsertore() throws IOException { - - String userstore = "DUMMY"; - String body = readResource("claim-management-add-local-claim-invalid-userstore.json"); - Response response = getResponseOfPost(CLAIM_DIALECTS_ENDPOINT_URI + LOCAL_CLAIMS_ENDPOINT_URI, body); - validateErrorResponse(response, HttpStatus.SC_BAD_REQUEST, "CMT-50026", userstore); - } - - @Test - public void testAddExternalClaimWithInvalidDialect() throws IOException { - - String body = readResource("claim-management-add-external-claim.json"); - Response response = getResponseOfPost(CLAIM_DIALECTS_ENDPOINT_URI + "/" + testDialectId + CLAIMS_ENDPOINT_URI - , body); - validateErrorResponse(response, HttpStatus.SC_NOT_FOUND, "CMT-50027", testDialectId); - } - - @Test - public void testRemoveLocalClaimWithExternalClaimAssociation() throws IOException { - - String mappedLocalClaimId = "aHR0cDovL3dzbzIub3JnL2NsYWltcy9lbWFpbGFkZHJlc3M"; - String dialectId = createDialect(); - String claimId = createExternalClaim(dialectId); - - Response response = - getResponseOfDelete(CLAIM_DIALECTS_ENDPOINT_URI + LOCAL_CLAIMS_ENDPOINT_URI + "/" + mappedLocalClaimId); - validateErrorResponse(response, HttpStatus.SC_BAD_REQUEST, "CMT-50031"); - - removeExternalClaim(dialectId, claimId); - removeDialect(dialectId); - } - - @Test - public void testAddExternalClaimWithInvalidMappedClaim() throws IOException { - - String dialectId = createDialect(); - - String body = readResource("claim-management-add-external-claim-invalid-mapped-claim.json"); - Response response = getResponseOfPost(CLAIM_DIALECTS_ENDPOINT_URI + "/" + dialectId + CLAIMS_ENDPOINT_URI, - body); - validateErrorResponse(response, HttpStatus.SC_BAD_REQUEST, "CMT-50036"); - - removeDialect(dialectId); - } - private String createDialect() throws IOException { String body = readResource("claim-management-add-dialect.json"); @@ -277,7 +397,7 @@ private void removeDialect(String dialectId) { .statusCode(HttpStatus.SC_NO_CONTENT); } - private String createExternalClaim(String dialectId) throws IOException { + private String createExternalClaimMappedToDefaultLocalClaim(String dialectId) throws IOException { String body = readResource("claim-management-add-external-claim.json"); Response response = getResponseOfPost(CLAIM_DIALECTS_ENDPOINT_URI + "/" + dialectId + @@ -292,6 +412,21 @@ private String createExternalClaim(String dialectId) throws IOException { return location.substring(location.lastIndexOf("/") + 1); } + private String createExternalClaimMappedToCustomLocalClaim(String dialectId) throws IOException { + + String body = readResource("claim-management-add-external-claim-mapped-to-custom-local-claim.json"); + Response response = getResponseOfPost(CLAIM_DIALECTS_ENDPOINT_URI + "/" + dialectId + + CLAIMS_ENDPOINT_URI, body); + response.then() + .log().ifValidationFails() + .assertThat() + .statusCode(HttpStatus.SC_CREATED) + .header(HttpHeaders.LOCATION, notNullValue()); + + String location = response.getHeader(HttpHeaders.LOCATION); + return location.substring(location.lastIndexOf("/") + 1); + } + private void removeExternalClaim(String dialectId, String externalClaimId) { getResponseOfDelete(CLAIM_DIALECTS_ENDPOINT_URI + "/" + dialectId + CLAIMS_ENDPOINT_URI + "/" + diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/idp/v1/IdPFailureTest.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/idp/v1/IdPFailureTest.java index 45623e50f00..807984c9599 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/idp/v1/IdPFailureTest.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/idp/v1/IdPFailureTest.java @@ -16,6 +16,7 @@ package org.wso2.identity.integration.test.rest.api.server.idp.v1; +import com.fasterxml.jackson.core.JsonProcessingException; import io.restassured.RestAssured; import io.restassured.response.Response; import org.apache.commons.lang.StringUtils; @@ -29,20 +30,40 @@ import org.testng.annotations.Factory; import org.testng.annotations.Test; import org.wso2.carbon.automation.engine.context.TestUserMode; +import org.wso2.identity.integration.test.rest.api.server.idp.v1.model.AuthenticationType; +import org.wso2.identity.integration.test.rest.api.server.idp.v1.model.Endpoint; +import org.wso2.identity.integration.test.rest.api.server.idp.v1.model.FederatedAuthenticatorRequest; +import org.wso2.identity.integration.test.rest.api.server.idp.v1.util.UserDefinedAuthenticatorPayload; import java.io.IOException; +import java.util.Base64; import java.util.HashMap; import java.util.Map; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.core.IsNull.notNullValue; +import static org.testng.Assert.assertNotNull; /** * Test class for Identity Provider Management REST APIs failure paths. */ public class IdPFailureTest extends IdPTestBase { + private static final String USERNAME = "username"; + private static final String PASSWORD = "password"; + private static final String FEDERATED_AUTHENTICATOR_ID_PLACEHOLDER = ""; + private static final String FEDERATED_AUTHENTICATOR_PLACEHOLDER = "\"\""; + private static final String FEDERATED_AUTHENTICATOR_PLACEHOLDER_1 = "\"\""; + private static final String FEDERATED_AUTHENTICATOR_PLACEHOLDER_2 = "\"\""; + private static final String IDP_NAME_PLACEHOLDER = ""; + private static final String CUSTOM_IDP_NAME = "CustomAuthIDP"; + private static final String USER_DEFINED_AUTHENTICATOR_ID_1 = "Y3VzdG9tQXV0aGVudGljYXRvcjE="; + private static final String USER_DEFINED_AUTHENTICATOR_ID_2 = "Y3VzdG9tQXV0aGVudGljYXRvcg=="; + private static final String SYSTEM_DEFINED_AUTHENTICATOR_ID = "R29vZ2xlT0lEQ0F1dGhlbnRpY2F0b3I"; + private static final String ENDPOINT_URI = "https://abc.com/authenticate"; private String idPId; + private String idpCreatePayload; + private static final String OIDC_IDP_ID = "T3BlbklEQ29ubmVjdEF1dGhlbnRpY2F0b3I"; @Factory(dataProvider = "restAPIUserConfigProvider") public IdPFailureTest(TestUserMode userMode) throws Exception { @@ -58,6 +79,7 @@ public IdPFailureTest(TestUserMode userMode) throws Exception { public void init() throws IOException { super.testInit(API_VERSION, swaggerDefinition, tenant); + idpCreatePayload = readResource("add-idp-with-custom-fed-auth.json"); } @AfterClass(alwaysRun = true) @@ -179,4 +201,400 @@ public void testPatchIdPNonExistentProperties() throws IOException { Response response = getResponseOfPatch(IDP_API_BASE_PATH + PATH_SEPARATOR + idPId, body); validateErrorResponse(response, HttpStatus.SC_NOT_FOUND, "IDP-65005", "JWKS URI"); } + + @Test + public void testAddIdPWithUserDefinedAuthenticatorWhenEndpointUriIsEmpty() throws IOException { + + UserDefinedAuthenticatorPayload userDefAuthPayload = createUserDefinedAuthenticatorPayload( + USER_DEFINED_AUTHENTICATOR_ID_1, + "", + "testUser", + "testPassword"); + Response response = createUserDefAuthenticator(CUSTOM_IDP_NAME, userDefAuthPayload); + response.then() + .log().ifValidationFails() + .assertThat() + .statusCode(HttpStatus.SC_BAD_REQUEST) + .body("message", equalTo("Invalid Request")) + .body("description", equalTo("must match \"^https?://.+\"")); + } + + @Test + public void testAddIdPWithUserDefinedAuthenticatorWhenEndpointUriIsInvalid() throws IOException { + + UserDefinedAuthenticatorPayload useDefAuthPayload = createUserDefinedAuthenticatorPayload( + USER_DEFINED_AUTHENTICATOR_ID_1, + "ftp://test.com", + "testUser", + "testPassword"); + Response response = createUserDefAuthenticator(CUSTOM_IDP_NAME, useDefAuthPayload); + response.then() + .log().ifValidationFails() + .assertThat() + .statusCode(HttpStatus.SC_BAD_REQUEST) + .body("message", equalTo("Invalid Request")) + .body("description", equalTo("must match \"^https?://.+\"")); + } + + @Test + public void testAddIdPWithUserDefinedAuthenticatorWhenEndpointConfigIsEmpty() throws IOException { + + UserDefinedAuthenticatorPayload userDefAuthPayload = + createUserDefinedAuthenticatorPayloadWithEmptyEndpointConfig(USER_DEFINED_AUTHENTICATOR_ID_1); + Response response = createUserDefAuthenticator(CUSTOM_IDP_NAME, userDefAuthPayload); + response.then() + .log().ifValidationFails() + .assertThat() + .statusCode(HttpStatus.SC_BAD_REQUEST) + .body("message", equalTo("No endpoint provided.")) + .body("description", equalTo("Endpoint configuration must be provided for the user defined " + + "federated authenticators " + new String(Base64.getDecoder().decode( + USER_DEFINED_AUTHENTICATOR_ID_1)) + ".")); + } + + @Test + public void testAddIdPWithUserDefinedAuthenticatorWhenAuthenticatorAuthDetailsIsEmpty() throws IOException { + + UserDefinedAuthenticatorPayload userDefAuthPayload = + createUserDefinedAuthenticatorPayloadWithEmptyAuthenticationProperties(USER_DEFINED_AUTHENTICATOR_ID_1, ENDPOINT_URI); + Response response = createUserDefAuthenticator(CUSTOM_IDP_NAME, userDefAuthPayload); + response.then() + .log().ifValidationFails() + .assertThat() + .statusCode(HttpStatus.SC_BAD_REQUEST) + .body("message", equalTo("Invalid Request")) + .body("description", equalTo("Property authentication cannot be null.")); + } + + @Test + public void testAddIdPWithUserDefinedAuthenticatorWhenAuthenticatorPasswordIsAbsent() + throws JsonProcessingException { + + UserDefinedAuthenticatorPayload userDefAuthPayload = createInvalidUserDefinedAuthenticatorPayload( + "USER", USER_DEFINED_AUTHENTICATOR_ID_1, ENDPOINT_URI, USERNAME, null); + Response response = createUserDefAuthenticator(CUSTOM_IDP_NAME, userDefAuthPayload); + response.then() + .log().ifValidationFails() + .assertThat() + .statusCode(HttpStatus.SC_BAD_REQUEST) + .body("message", equalTo("Invalid input.")) + .body("description", equalTo("The property password must be provided as an authentication " + + "property for the BASIC authentication type.")); + } + + @Test + public void testAddIdPWithUserDefinedAuthenticatorWhenAuthenticatorPasswordIsEmpty() + throws JsonProcessingException { + + UserDefinedAuthenticatorPayload userDefAuthPayload = createInvalidUserDefinedAuthenticatorPayload( + "USER", USER_DEFINED_AUTHENTICATOR_ID_1, ENDPOINT_URI, USERNAME, ""); + Response response = createUserDefAuthenticator(CUSTOM_IDP_NAME, userDefAuthPayload); + response.then() + .log().ifValidationFails() + .assertThat() + .statusCode(HttpStatus.SC_BAD_REQUEST) + .body("message", equalTo("Invalid input.")) + .body("description", equalTo("The Property password cannot be blank.")); + } + + @Test + public void testAddIdPWithUserDefinedAuthenticatorWithExistingAuthenticatorName() throws IOException { + + UserDefinedAuthenticatorPayload useDefAuthPayload = createUserDefinedAuthenticatorPayload( + USER_DEFINED_AUTHENTICATOR_ID_1, ENDPOINT_URI, "testUser", "testPassword"); + Response response = createUserDefAuthenticator(CUSTOM_IDP_NAME, useDefAuthPayload); + response.then() + .log().ifValidationFails() + .assertThat() + .statusCode(HttpStatus.SC_CREATED) + .header(HttpHeaders.LOCATION, notNullValue()); + String location = response.getHeader(HttpHeaders.LOCATION); + assertNotNull(location); + String customIdPId = location.substring(location.lastIndexOf("/") + 1); + assertNotNull(customIdPId); + + // duplicate the authenticator creation + UserDefinedAuthenticatorPayload duplicateUseDefAuthPayload = + createUserDefinedAuthenticatorPayload(USER_DEFINED_AUTHENTICATOR_ID_1, + "https://xyz.com/authenticate", + "testUser1", + "testPassword1"); + Response responseOfDuplicate = createUserDefAuthenticator("CustomAuthIDP2", + duplicateUseDefAuthPayload); + responseOfDuplicate.then() + .log().ifValidationFails() + .assertThat() + .statusCode(HttpStatus.SC_BAD_REQUEST) + .body("message", equalTo("Federated authenticator name " + + new String(Base64.getDecoder().decode(USER_DEFINED_AUTHENTICATOR_ID_1)) + " is already taken.")); + + deleteCreatedIdP(customIdPId); + } + + @Test + public void testAddIdPWithUserDefinedAuthenticatorWithMultipleAuthenticators() throws IOException { + + String idpCreateErrorPayload = readResource("add-idp-with-custom-fed-multi-auth.json"); + UserDefinedAuthenticatorPayload userDefinedAuthenticatorPayload1 = createUserDefinedAuthenticatorPayload( + USER_DEFINED_AUTHENTICATOR_ID_1, + ENDPOINT_URI, + "testUser", + "testPassword"); + UserDefinedAuthenticatorPayload userDefinedAuthenticatorPayload2 = createUserDefinedAuthenticatorPayload( + USER_DEFINED_AUTHENTICATOR_ID_2, + ENDPOINT_URI, + "testUser", + "testPassword"); + + Response response = createMultiUserDefAuthenticators("CustomAuthIDPX", idpCreateErrorPayload, + userDefinedAuthenticatorPayload1, userDefinedAuthenticatorPayload2); + response.then() + .log().ifValidationFails() + .assertThat() + .statusCode(HttpStatus.SC_BAD_REQUEST) + .body("message", equalTo("Multiple authenticators found.")); + } + + @Test + public void testAddUserDefAuthenticatorWithSystemProperty() throws JsonProcessingException { + + UserDefinedAuthenticatorPayload useDefAuthPayload = createInvalidUserDefinedAuthenticatorPayload( + "SYSTEM", USER_DEFINED_AUTHENTICATOR_ID_1, ENDPOINT_URI, USERNAME, PASSWORD); + Response response = createUserDefAuthenticator(CUSTOM_IDP_NAME, useDefAuthPayload); + response.then() + .log().ifValidationFails() + .assertThat() + .statusCode(HttpStatus.SC_BAD_REQUEST) + .body("message", equalTo("No endpoint configuration is allowed.")) + .body("description", equalTo("No endpoint configuration must be provided for the system defined " + + "federated authenticators " + + new String(Base64.getDecoder().decode(USER_DEFINED_AUTHENTICATOR_ID_1)) + ".")); + } + + @Test + public void testAddUserDefAuthenticatorWithExistingSystemDefAuthenticatorName() throws JsonProcessingException { + + UserDefinedAuthenticatorPayload useDefAuthPayload = createUserDefinedAuthenticatorPayload( + SYSTEM_DEFINED_AUTHENTICATOR_ID, ENDPOINT_URI, "testUser", "testPassword"); + Response response = createUserDefAuthenticator(CUSTOM_IDP_NAME, useDefAuthPayload); + response.then() + .log().ifValidationFails() + .assertThat() + .statusCode(HttpStatus.SC_BAD_REQUEST) + .body("message", equalTo("Federated authenticator name " + new String(Base64.getDecoder(). + decode(SYSTEM_DEFINED_AUTHENTICATOR_ID)) + " is already taken.")); + } + + /** + * Create multiple user-defined authenticators for an IdP and sends a POST request to the IDP API. + * + * @param idpName Name of the identity provider. + * @param idpCreatePayload Base payload template for the identity provider. + * @param userDefinedAuthenticatorPayload1 First authenticator payload. + * @param userDefinedAuthenticatorPayload2 Second authenticator payload. + * @return Response received from the API call. + * @throws JsonProcessingException If there's an error while processing the JSON. + */ + private Response createMultiUserDefAuthenticators(String idpName, String idpCreatePayload, + UserDefinedAuthenticatorPayload + userDefinedAuthenticatorPayload1, + UserDefinedAuthenticatorPayload userDefinedAuthenticatorPayload2) + throws JsonProcessingException { + + String body = idpCreatePayload.replace(FEDERATED_AUTHENTICATOR_ID_PLACEHOLDER, + userDefinedAuthenticatorPayload1.getAuthenticatorId()); + body = body.replace(FEDERATED_AUTHENTICATOR_PLACEHOLDER_1, + userDefinedAuthenticatorPayload1.convertToJasonPayload()); + body = body.replace(FEDERATED_AUTHENTICATOR_PLACEHOLDER_2, + userDefinedAuthenticatorPayload2.convertToJasonPayload()); + body = body.replace(IDP_NAME_PLACEHOLDER, idpName); + return getResponseOfPost(IDP_API_BASE_PATH, body); + } + + /** + * Create a user-defined authenticator payload with provided details. + * + * @param id Authenticator ID. + * @param endpoint_uri Endpoint URI for the authenticator. + * @param username Username for basic authentication. + * @param password Password for basic authentication. + * @return A user-defined authenticator payload. + */ + private UserDefinedAuthenticatorPayload createUserDefinedAuthenticatorPayload(String id, String endpoint_uri, + String username, String password) { + + UserDefinedAuthenticatorPayload userDefinedAuthenticatorPayload = new UserDefinedAuthenticatorPayload(); + userDefinedAuthenticatorPayload.setIsEnabled(true); + userDefinedAuthenticatorPayload.setAuthenticatorId(id); + userDefinedAuthenticatorPayload.setDefinedBy(FederatedAuthenticatorRequest.DefinedByEnum.USER.toString()); + + Endpoint endpoint = new Endpoint(); + endpoint.setUri(endpoint_uri); + AuthenticationType authenticationType = new AuthenticationType(); + authenticationType.setType(AuthenticationType.TypeEnum.BASIC); + Map properties = new HashMap<>(); + properties.put(USERNAME, username); + properties.put(PASSWORD, password); + authenticationType.setProperties(properties); + endpoint.authentication(authenticationType); + userDefinedAuthenticatorPayload.setEndpoint(endpoint); + + return userDefinedAuthenticatorPayload; + } + + /** + * Creates an invalid user-defined authenticator payload. + * This method enables the creation of an invalid authenticator payload, either by defining the definedBy property + * as SYSTEM or by leaving the password field empty. + * + * @param definedBy Entity that defines the authenticator, either "SYSTEM" or "USER". + * @param id IDof the authenticator. + * @param endpoint_uri URI of the endpoint. + * @param username Username for basic authentication. + * @param password Password for basic authentication. If empty, no password will be set. + * @return A {@link UserDefinedAuthenticatorPayload} containing the invalid authenticator setup. + */ + private UserDefinedAuthenticatorPayload createInvalidUserDefinedAuthenticatorPayload( + String definedBy, String id, String endpoint_uri, String username, String password) { + + UserDefinedAuthenticatorPayload userDefinedAuthenticatorPayload = new UserDefinedAuthenticatorPayload(); + userDefinedAuthenticatorPayload.setIsEnabled(true); + userDefinedAuthenticatorPayload.setAuthenticatorId(id); + switch (definedBy) { + case "SYSTEM": + userDefinedAuthenticatorPayload.setDefinedBy( + FederatedAuthenticatorRequest.DefinedByEnum.SYSTEM.toString()); + break; + case "USER": + userDefinedAuthenticatorPayload.setDefinedBy( + FederatedAuthenticatorRequest.DefinedByEnum.USER.toString()); + break; + } + + Endpoint endpoint = new Endpoint(); + endpoint.setUri(endpoint_uri); + AuthenticationType authenticationType = new AuthenticationType(); + authenticationType.setType(AuthenticationType.TypeEnum.BASIC); + Map properties = new HashMap<>(); + properties.put(USERNAME, username); + if (password != null) { + properties.put(PASSWORD, password); + } + authenticationType.setProperties(properties); + endpoint.authentication(authenticationType); + userDefinedAuthenticatorPayload.setEndpoint(endpoint); + + return userDefinedAuthenticatorPayload; + } + + /** + * Create a user-defined authenticator payload with an empty endpoint configuration. + * + * @param id Authenticator ID. + * @return A user-defined authenticator payload with no endpoint configuration. + */ + private UserDefinedAuthenticatorPayload createUserDefinedAuthenticatorPayloadWithEmptyEndpointConfig(String id) { + + UserDefinedAuthenticatorPayload userDefinedAuthenticatorPayload = new UserDefinedAuthenticatorPayload(); + userDefinedAuthenticatorPayload.setIsEnabled(true); + userDefinedAuthenticatorPayload.setAuthenticatorId(id); + userDefinedAuthenticatorPayload.setDefinedBy(FederatedAuthenticatorRequest.DefinedByEnum.USER.toString()); + + return userDefinedAuthenticatorPayload; + } + + /** + * Create a user-defined authenticator payload with an endpoint URI with empty authentication properties. + * + * @param id Authenticator ID. + * @param endpoint_uri The endpoint URI for the authenticator. + * @return A user-defined authenticator payload with endpoint URI but without authentication details. + */ + private UserDefinedAuthenticatorPayload createUserDefinedAuthenticatorPayloadWithEmptyAuthenticationProperties( + String id, String endpoint_uri) { + + UserDefinedAuthenticatorPayload userDefinedAuthenticatorPayload = new UserDefinedAuthenticatorPayload(); + userDefinedAuthenticatorPayload.setIsEnabled(true); + userDefinedAuthenticatorPayload.setAuthenticatorId(id); + userDefinedAuthenticatorPayload.setDefinedBy(FederatedAuthenticatorRequest.DefinedByEnum.USER.toString()); + + Endpoint endpoint = new Endpoint(); + endpoint.setUri(endpoint_uri); + userDefinedAuthenticatorPayload.setEndpoint(endpoint); + + return userDefinedAuthenticatorPayload; + } + + /** + * Create a user-defined authenticator and sends a POST request to the IDP API. + * + * @param idpName Name of the identity provider. + * @param userDefinedAuthenticatorPayload Payload containing authenticator details. + * @return Response received from the API call. + * @throws JsonProcessingException If there's an error while processing the JSON. + */ + private Response createUserDefAuthenticator(String idpName, UserDefinedAuthenticatorPayload + userDefinedAuthenticatorPayload) throws JsonProcessingException { + + String body = idpCreatePayload.replace(FEDERATED_AUTHENTICATOR_ID_PLACEHOLDER, + userDefinedAuthenticatorPayload.getAuthenticatorId()); + body = body.replace(FEDERATED_AUTHENTICATOR_PLACEHOLDER, + userDefinedAuthenticatorPayload.convertToJasonPayload()); + body = body.replace(IDP_NAME_PLACEHOLDER, idpName); + return getResponseOfPostNoFilter(IDP_API_BASE_PATH, body); + } + + @Test + public void testUpdateIdPWithDuplicateOIDCScopes() throws IOException { + + String body = readResource("add-idp-oidc-standard-based.json"); + Response response = getResponseOfPost(IDP_API_BASE_PATH, body); + response.then() + .log().ifValidationFails() + .assertThat() + .statusCode(HttpStatus.SC_CREATED) + .header(HttpHeaders.LOCATION, notNullValue()); + + String location = response.getHeader(HttpHeaders.LOCATION); + assertNotNull(location); + String oidcIdPId = location.substring(location.lastIndexOf("/") + 1); + assertNotNull(oidcIdPId); + + // update the OIDC IDP with duplicated scopes + String updateBody = readResource("update-idp-oidc-standard-based-duplicated-scopes.json"); + Response updateResponse = getResponseOfPut(IDP_API_BASE_PATH + PATH_SEPARATOR + oidcIdPId + + PATH_SEPARATOR + IDP_FEDERATED_AUTHENTICATORS_PATH + PATH_SEPARATOR + OIDC_IDP_ID, updateBody); + updateResponse.then() + .log().ifValidationFails() + .assertThat() + .statusCode(HttpStatus.SC_BAD_REQUEST) + .body("message", equalTo("Duplicate OIDC Scopes.")) + .body("description", equalTo("Cannot set scopes in both Scopes and Additional Query Parameters. " + + "Recommend to use Scopes field.")); + + deleteCreatedIdP(oidcIdPId); + } + + /** + * Deletes an Identity Provider by its ID and verifies the deletion. + * + * @param idPId ID of the Identity Provider to be deleted. + */ + private void deleteCreatedIdP(String idPId) { + + Response response = getResponseOfDelete(IDP_API_BASE_PATH + PATH_SEPARATOR + idPId); + response.then() + .log().ifValidationFails() + .assertThat() + .statusCode(HttpStatus.SC_NO_CONTENT); + + Response responseOfGet = getResponseOfGet(IDP_API_BASE_PATH + PATH_SEPARATOR + idPId); + responseOfGet.then() + .log().ifValidationFails() + .assertThat() + .statusCode(HttpStatus.SC_NOT_FOUND) + .body("message", equalTo("Resource not found.")) + .body("description", equalTo("Unable to find a resource matching the provided identity " + + "provider identifier " + idPId + ".")); + } } diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/idp/v1/IdPSuccessTest.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/idp/v1/IdPSuccessTest.java index ba7dfcc0609..69ca753532a 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/idp/v1/IdPSuccessTest.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/idp/v1/IdPSuccessTest.java @@ -16,6 +16,7 @@ package org.wso2.identity.integration.test.rest.api.server.idp.v1; +import com.fasterxml.jackson.core.JsonProcessingException; import io.restassured.RestAssured; import io.restassured.response.Response; import org.apache.commons.lang.StringUtils; @@ -29,11 +30,19 @@ import org.testng.annotations.Factory; import org.testng.annotations.Test; import org.wso2.carbon.automation.engine.context.TestUserMode; +import org.wso2.identity.integration.test.rest.api.server.idp.v1.model.AuthenticationType; +import org.wso2.identity.integration.test.rest.api.server.idp.v1.model.Endpoint; +import org.wso2.identity.integration.test.rest.api.server.idp.v1.model.FederatedAuthenticatorRequest; +import org.wso2.identity.integration.test.rest.api.server.idp.v1.util.UserDefinedAuthenticatorPayload; import java.io.IOException; +import java.util.Base64; +import java.util.Collections; import java.util.HashMap; import java.util.Map; +import javax.xml.xpath.XPathExpressionException; + import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.core.IsNull.notNullValue; import static org.hamcrest.core.IsNull.nullValue; @@ -44,8 +53,25 @@ */ public class IdPSuccessTest extends IdPTestBase { + private static final String FEDERATED_AUTHENTICATOR_ID_PLACEHOLDER = ""; + private static final String FEDERATED_AUTHENTICATOR_PLACEHOLDER = "\"\""; + private static final String IDP_NAME_PLACEHOLDER = ""; + private static final String FEDERATED_AUTHENTICATOR_ID = "Y3VzdG9tQXV0aGVudGljYXRvcg"; + private static final String CUSTOM_IDP_NAME = "Custom Auth IDP"; + private static final String ENDPOINT_URI = "https://abc.com/authenticate"; + private static final String UPDATED_ENDPOINT_URI = "https://xyz.com/authenticate"; + private static final String USERNAME = "username"; + private static final String PASSWORD = "password"; + private static final String ACCESS_TOKEN = "accessToken"; + private static final String USERNAME_VALUE = "testUser"; + private static final String ACCESS_TOKEN_VALUE = "testBearerToken"; + private static final String PASSWORD_VALUE = "testPassword"; + private static final String IDP_NAME = "Google"; private String idPId; + private String customIdPId; private String idPTemplateId; + private UserDefinedAuthenticatorPayload userDefinedAuthenticatorPayload; + private String idpCreatePayload; @Factory(dataProvider = "restAPIUserConfigProvider") public IdPSuccessTest(TestUserMode userMode) throws Exception { @@ -61,6 +87,50 @@ public IdPSuccessTest(TestUserMode userMode) throws Exception { public void init() throws IOException { super.testInit(API_VERSION, swaggerDefinition, tenant); + userDefinedAuthenticatorPayload = createUserDefinedAuthenticatorPayloadWithBasic(ENDPOINT_URI); + idpCreatePayload = readResource("add-idp-with-custom-fed-auth.json"); + } + + private UserDefinedAuthenticatorPayload createUserDefinedAuthenticatorPayloadWithBasic(String endpointUri) { + + UserDefinedAuthenticatorPayload userDefinedAuthenticatorPayload = new UserDefinedAuthenticatorPayload(); + userDefinedAuthenticatorPayload.setIsEnabled(true); + userDefinedAuthenticatorPayload.setAuthenticatorId(FEDERATED_AUTHENTICATOR_ID); + userDefinedAuthenticatorPayload.setDefinedBy(FederatedAuthenticatorRequest.DefinedByEnum.USER.toString()); + + Endpoint endpoint = new Endpoint(); + endpoint.setUri(endpointUri); + AuthenticationType authenticationType = new AuthenticationType(); + authenticationType.setType(AuthenticationType.TypeEnum.BASIC); + Map properties = new HashMap<>(); + properties.put(USERNAME, USERNAME_VALUE); + properties.put(PASSWORD, PASSWORD_VALUE); + authenticationType.setProperties(properties); + endpoint.authentication(authenticationType); + userDefinedAuthenticatorPayload.setEndpoint(endpoint); + + return userDefinedAuthenticatorPayload; + } + + private UserDefinedAuthenticatorPayload createUserDefinedAuthenticatorPayloadWithBearer(String endpointUri) { + + UserDefinedAuthenticatorPayload userDefinedAuthenticatorPayload = new UserDefinedAuthenticatorPayload(); + userDefinedAuthenticatorPayload.setIsEnabled(true); + userDefinedAuthenticatorPayload.setAuthenticatorId(FEDERATED_AUTHENTICATOR_ID); + userDefinedAuthenticatorPayload.setDefinedBy(FederatedAuthenticatorRequest.DefinedByEnum.USER.toString()); + + Endpoint endpoint = new Endpoint(); + endpoint.setUri(endpointUri); + AuthenticationType authenticationType = new AuthenticationType(); + authenticationType.setType(AuthenticationType.TypeEnum.BEARER); + Map properties = new HashMap<>(); + authenticationType.setType(AuthenticationType.TypeEnum.BEARER); + properties.put(ACCESS_TOKEN, ACCESS_TOKEN_VALUE); + authenticationType.setProperties(properties); + endpoint.authentication(authenticationType); + userDefinedAuthenticatorPayload.setEndpoint(endpoint); + + return userDefinedAuthenticatorPayload; } @AfterClass(alwaysRun = true) @@ -256,6 +326,88 @@ public void testGetMetaOutboundConnector() throws IOException { .body("rulesEnabled", equalTo(false)); } + @Test + public void testAddIdPWithUserDefinedAuthenticator() throws IOException { + + String body = idpCreatePayload.replace(FEDERATED_AUTHENTICATOR_ID_PLACEHOLDER, + userDefinedAuthenticatorPayload.getAuthenticatorId()); + body = body.replace(FEDERATED_AUTHENTICATOR_PLACEHOLDER, + userDefinedAuthenticatorPayload.convertToJasonPayload()); + body = body.replace(IDP_NAME_PLACEHOLDER, CUSTOM_IDP_NAME); + Response response = getResponseOfPost(IDP_API_BASE_PATH, body); + response.then() + .log().ifValidationFails() + .assertThat() + .statusCode(HttpStatus.SC_CREATED) + .header(HttpHeaders.LOCATION, notNullValue()); + + String location = response.getHeader(HttpHeaders.LOCATION); + assertNotNull(location); + customIdPId = location.substring(location.lastIndexOf("/") + 1); + assertNotNull(customIdPId); + } + + @Test(dependsOnMethods = "testAddIdPWithUserDefinedAuthenticator") + public void testGetUserDefinedAuthenticatorsOfIdP() throws XPathExpressionException { + + Response response = getResponseOfGet(IDP_API_BASE_PATH + PATH_SEPARATOR + customIdPId + + PATH_SEPARATOR + IDP_FEDERATED_AUTHENTICATORS_PATH); + + response.then() + .log().ifValidationFails() + .assertThat() + .statusCode(HttpStatus.SC_OK) + .body("defaultAuthenticatorId", equalTo(FEDERATED_AUTHENTICATOR_ID)) + .body("authenticators.find { it.authenticatorId == '" + FEDERATED_AUTHENTICATOR_ID + "' }.name", + equalTo(new String(Base64.getDecoder().decode(FEDERATED_AUTHENTICATOR_ID)))) + .body("authenticators.find { it.authenticatorId == '" + FEDERATED_AUTHENTICATOR_ID + "' }.isEnabled", + equalTo(true)) + .body("authenticators.find { it.authenticatorId == '" + FEDERATED_AUTHENTICATOR_ID + "' }.self", + equalTo(getTenantedRelativePath("/api/server/v1/identity-providers/" + + customIdPId + "/federated-authenticators/" + FEDERATED_AUTHENTICATOR_ID, + context.getContextTenant().getDomain()))); + } + + @Test(dependsOnMethods = "testGetUserDefinedAuthenticatorsOfIdP") + public void testUpdateUserDefinedAuthenticatorOfIdP() throws JsonProcessingException { + + Response response = getResponseOfPut(IDP_API_BASE_PATH + PATH_SEPARATOR + customIdPId + + PATH_SEPARATOR + IDP_FEDERATED_AUTHENTICATORS_PATH + PATH_SEPARATOR + FEDERATED_AUTHENTICATOR_ID, + createUserDefinedAuthenticatorPayloadWithBearer(UPDATED_ENDPOINT_URI) + .convertToJasonPayload()); + + response.then() + .log().ifValidationFails() + .assertThat() + .statusCode(HttpStatus.SC_OK) + .body("authenticatorId", equalTo(FEDERATED_AUTHENTICATOR_ID)) + .body("name", equalTo(new String(Base64.getDecoder().decode(FEDERATED_AUTHENTICATOR_ID)))) + .body("definedBy", equalTo("USER")) + .body("endpoint.uri", equalTo(UPDATED_ENDPOINT_URI)) + .body("endpoint.authentication.type", equalTo(AuthenticationType.TypeEnum.BEARER.value())); + } + + @Test(dependsOnMethods = {"testGetIdPs", "testUpdateUserDefinedAuthenticatorOfIdP"}) + public void testDeleteIdPWithUserDefinedAuthenticator() { + + Response response = getResponseOfDelete(IDP_API_BASE_PATH + PATH_SEPARATOR + customIdPId); + response.then() + .log().ifValidationFails() + .assertThat() + .statusCode(HttpStatus.SC_NO_CONTENT); + + Response responseOfGet = getResponseOfGet(IDP_API_BASE_PATH + PATH_SEPARATOR + customIdPId); + responseOfGet.then() + .log().ifValidationFails() + .assertThat() + .assertThat() + .statusCode(HttpStatus.SC_NOT_FOUND) + .body("message", equalTo("Resource not found.")) + .body("description", equalTo("Unable to find a resource matching the provided identity " + + "provider identifier " + customIdPId + ".")); + + } + @Test(dependsOnMethods = {"testGetMetaOutboundConnector"}) public void testAddIdP() throws IOException { @@ -286,6 +438,8 @@ public void testGetIdP() throws IOException { .body("description", equalTo("IDP for Google Federation")) .body("isEnabled", equalTo(true)) .body("isPrimary", equalTo(false)) + .body("federatedAuthenticators.authenticators.find { it.authenticatorId == '" + + SAMPLE_FEDERATED_AUTHENTICATOR_ID + "' }.definedBy", equalTo("SYSTEM")) .body("image", equalTo("google-logo-url")) .body("isFederationHub", equalTo(false)) .body("homeRealmIdentifier", equalTo("localhost")) @@ -296,6 +450,7 @@ public void testGetIdP() throws IOException { public void testGetIdPs() throws Exception { String baseIdentifier = "identityProviders.find{ it.id == '" + idPId + "' }."; + String baseIdentifierUserDef = "identityProviders.find{ it.id == '" + customIdPId + "' }."; Response response = getResponseOfGet(IDP_API_BASE_PATH); response.then() .log().ifValidationFails() @@ -306,6 +461,27 @@ public void testGetIdPs() throws Exception { .body(baseIdentifier + "isEnabled", equalTo(true)) .body(baseIdentifier + "image", equalTo("google-logo-url")) .body(baseIdentifier + "self", equalTo(getTenantedRelativePath( + "/api/server/v1/identity-providers/" + idPId, + context.getContextTenant().getDomain()))) + .body(baseIdentifierUserDef + "name", equalTo(CUSTOM_IDP_NAME)) + .body(baseIdentifierUserDef + "isEnabled", equalTo(true)) + .body(baseIdentifierUserDef + "self", equalTo(getTenantedRelativePath( + "/api/server/v1/identity-providers/" + customIdPId, + context.getContextTenant().getDomain()))); + } + + @Test(dependsOnMethods = "testGetIdP") + public void testSearchAllIdPs() throws XPathExpressionException { + + Response response = getResponseOfGetWithQueryParams(IDP_API_BASE_PATH, Collections.singletonMap("filter", + "name sw " + IDP_NAME)); + response.then() + .log().ifValidationFails() + .assertThat() + .statusCode(HttpStatus.SC_OK) + .body("identityProviders.find { it.id == '" + idPId + "' }.name", equalTo(IDP_NAME)) + .body("identityProviders.find { it.id == '" + idPId + "' }.isEnabled", equalTo(true)) + .body("identityProviders.find { it.id == '" + idPId + "' }.self", equalTo(getTenantedRelativePath( "/api/server/v1/identity-providers/" + idPId, context.getContextTenant().getDomain()))); } diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/idp/v1/model/AuthenticationType.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/idp/v1/model/AuthenticationType.java new file mode 100644 index 00000000000..67232e2a518 --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/idp/v1/model/AuthenticationType.java @@ -0,0 +1,162 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.identity.integration.test.rest.api.server.idp.v1.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModelProperty; + +import javax.validation.Valid; +import javax.validation.constraints.NotNull; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import javax.xml.bind.annotation.XmlType; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + +public class AuthenticationType { + + + @XmlType(name="TypeEnum") + @XmlEnum(String.class) + public enum TypeEnum { + + @XmlEnumValue("NONE") NONE(String.valueOf("NONE")), @XmlEnumValue("BEARER") BEARER(String.valueOf("BEARER")), @XmlEnumValue("API_KEY") API_KEY(String.valueOf("API_KEY")), @XmlEnumValue("BASIC") BASIC(String.valueOf("BASIC")); + + + private String value; + + TypeEnum(String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static TypeEnum fromValue(String value) { + for (TypeEnum b : TypeEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + } + + private TypeEnum type; + private Map properties = new HashMap<>(); + + + /** + **/ + public AuthenticationType type(TypeEnum type) { + + this.type = type; + return this; + } + + @ApiModelProperty(example = "BASIC", required = true, value = "") + @JsonProperty("type") + @Valid + @NotNull(message = "Property type cannot be null.") + + public TypeEnum getType() { + return type; + } + public void setType(TypeEnum type) { + this.type = type; + } + + /** + **/ + public AuthenticationType properties(Map properties) { + + this.properties = properties; + return this; + } + + @ApiModelProperty(example = "{\"username\":\"auth_username\",\"password\":\"auth_password\"}", required = true, value = "") + @JsonProperty("properties") + @Valid + @NotNull(message = "Property properties cannot be null.") + + public Map getProperties() { + return properties; + } + public void setProperties(Map properties) { + this.properties = properties; + } + + + public AuthenticationType putPropertiesItem(String key, Object propertiesItem) { + this.properties.put(key, propertiesItem); + return this; + } + + + + @Override + public boolean equals(java.lang.Object o) { + + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AuthenticationType authenticationType = (AuthenticationType) o; + return Objects.equals(this.type, authenticationType.type) && + Objects.equals(this.properties, authenticationType.properties); + } + + @Override + public int hashCode() { + return Objects.hash(type, properties); + } + + @Override + public String toString() { + + StringBuilder sb = new StringBuilder(); + sb.append("class AuthenticationType {\n"); + + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" properties: ").append(toIndentedString(properties)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n"); + } +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/action/management/v1/model/AuthenticationTypeProperties.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/idp/v1/model/Endpoint.java similarity index 52% rename from modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/action/management/v1/model/AuthenticationTypeProperties.java rename to modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/idp/v1/model/Endpoint.java index 48f7fec9257..66be70e6f61 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/action/management/v1/model/AuthenticationTypeProperties.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/idp/v1/model/Endpoint.java @@ -16,47 +16,59 @@ * under the License. */ -package org.wso2.identity.integration.test.rest.api.server.action.management.v1.model; +package org.wso2.identity.integration.test.rest.api.server.idp.v1.model; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModelProperty; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; - import javax.validation.Valid; +import javax.validation.constraints.Pattern; +import java.util.Objects; -public class AuthenticationTypeProperties { +public class Endpoint { - private Map properties = null; + private String uri; + private AuthenticationType authentication; /** **/ - public AuthenticationTypeProperties properties(Map properties) { + public Endpoint uri(String uri) { - this.properties = properties; + this.uri = uri; return this; } - @ApiModelProperty(example = "{\"username\":\"auth_username\",\"password\":\"auth_username\"}", value = "") - @JsonProperty("properties") + @ApiModelProperty(example = "https://abc.com/token", value = "") + @JsonProperty("uri") @Valid - public Map getProperties() { - return properties; + @Pattern(regexp="^https?://.+") + public String getUri() { + return uri; } - public void setProperties(Map properties) { - this.properties = properties; + public void setUri(String uri) { + this.uri = uri; } - public AuthenticationTypeProperties putPropertiesItem(String key, Object propertiesItem) { - if (this.properties == null) { - this.properties = new HashMap(); - } - this.properties.put(key, propertiesItem); + /** + **/ + public Endpoint authentication(AuthenticationType authentication) { + + this.authentication = authentication; return this; } + @ApiModelProperty(value = "") + @JsonProperty("authentication") + @Valid + public AuthenticationType getAuthentication() { + return authentication; + } + public void setAuthentication(AuthenticationType authentication) { + this.authentication = authentication; + } + + + @Override public boolean equals(java.lang.Object o) { @@ -66,22 +78,24 @@ public boolean equals(java.lang.Object o) { if (o == null || getClass() != o.getClass()) { return false; } - AuthenticationTypeProperties authenticationTypeProperties = (AuthenticationTypeProperties) o; - return Objects.equals(this.properties, authenticationTypeProperties.properties); + Endpoint endpoint = (Endpoint) o; + return Objects.equals(this.uri, endpoint.uri) && + Objects.equals(this.authentication, endpoint.authentication); } @Override public int hashCode() { - return Objects.hash(properties); + return Objects.hash(uri, authentication); } @Override public String toString() { StringBuilder sb = new StringBuilder(); - sb.append("class AuthenticationTypeProperties {\n"); + sb.append("class Endpoint {\n"); - sb.append(" properties: ").append(toIndentedString(properties)).append("\n"); + sb.append(" uri: ").append(toIndentedString(uri)).append("\n"); + sb.append(" authentication: ").append(toIndentedString(authentication)).append("\n"); sb.append("}"); return sb.toString(); } @@ -95,6 +109,6 @@ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } - return o.toString(); + return o.toString().replace("\n", "\n"); } } diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/idp/v1/model/FederatedAuthenticatorRequest.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/idp/v1/model/FederatedAuthenticatorRequest.java index d281b5611fb..9c49cdfdbf2 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/idp/v1/model/FederatedAuthenticatorRequest.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/idp/v1/model/FederatedAuthenticatorRequest.java @@ -23,6 +23,9 @@ import org.wso2.identity.integration.test.rest.api.server.application.management.v1.model.OpenIDConnectConfiguration; import javax.validation.Valid; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import javax.xml.bind.annotation.XmlType; import java.util.ArrayList; import java.util.List; import java.util.Objects; @@ -107,6 +110,38 @@ public String toString() { "}"; } + @XmlType(name="DefinedByEnum") + @XmlEnum(String.class) + public enum DefinedByEnum { + + @XmlEnumValue("SYSTEM") SYSTEM(String.valueOf("SYSTEM")), @XmlEnumValue("USER") USER(String.valueOf("USER")); + + + private String value; + + DefinedByEnum(String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static DefinedByEnum fromValue(String value) { + for (DefinedByEnum b : DefinedByEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + } + /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). @@ -125,6 +160,8 @@ public static class FederatedAuthenticator { private Boolean isEnabled = false; private Boolean isDefault = false; private List properties = null; + private DefinedByEnum definedBy; + private Endpoint endpoint; /** * @@ -234,16 +271,63 @@ public FederatedAuthenticator addProperty(Property property) { return this; } + /** + * + **/ + public FederatedAuthenticator definedBy(DefinedByEnum definedBy) { + + this.definedBy = definedBy; + return this; + } + + @ApiModelProperty(value = "") + @JsonProperty("definedBy") + @Valid + public DefinedByEnum getDefinedBy() { + return definedBy; + } + public void setDefinedBy(DefinedByEnum definedBy) { + this.definedBy = definedBy; + } + + /** + **/ + public FederatedAuthenticator endpoint(Endpoint endpoint) { + + this.endpoint = endpoint; + return this; + } + + @ApiModelProperty(value = "") + @JsonProperty("endpoint") + @Valid + public Endpoint getEndpoint() { + return endpoint; + } + public void setEndpoint(Endpoint endpoint) { + this.endpoint = endpoint; + } + @Override public String toString() { - return "class FederatedAuthenticator {\n" + + String classToString = "class FederatedAuthenticator {\n" + " authenticatorId: " + toIndentedString(authenticatorId) + "\n" + " name: " + toIndentedString(name) + "\n" + " isEnabled: " + toIndentedString(isEnabled) + "\n" + - " isDefault: " + toIndentedString(isDefault) + "\n" + - " properties: " + toIndentedString(properties) + "\n" + - "}"; + + " isDefault: " + toIndentedString(isDefault) + "\n"; + if (properties != null) { + classToString += " properties: " + toIndentedString(properties) + "\n"; + } + if (definedBy != null) { + classToString += " definedBy: " + toIndentedString(definedBy) + "\n"; + } + if (endpoint != null) { + classToString += " endpoint: " + toIndentedString(endpoint) + "\n"; + } + + return classToString + "}"; } } } diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/idp/v1/util/UserDefinedAuthenticatorPayload.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/idp/v1/util/UserDefinedAuthenticatorPayload.java new file mode 100644 index 00000000000..79bcb71aec3 --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/idp/v1/util/UserDefinedAuthenticatorPayload.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.identity.integration.test.rest.api.server.idp.v1.util; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.wso2.identity.integration.test.rest.api.server.idp.v1.model.Endpoint; + +public class UserDefinedAuthenticatorPayload { + + @JsonProperty("isEnabled") + private Boolean isEnabled; + + @JsonProperty("authenticatorId") + private String authenticatorId; + + @JsonProperty("definedBy") + private String definedBy; + + @JsonProperty("endpoint") + private Endpoint endpoint; + + public Boolean getIsEnabled() { + return isEnabled; + } + + public void setIsEnabled(Boolean isEnabled) { + this.isEnabled = isEnabled; + } + + public String getAuthenticatorId() { + return authenticatorId; + } + + public void setAuthenticatorId(String authenticatorId) { + this.authenticatorId = authenticatorId; + } + + public String getDefinedBy() { + return definedBy; + } + + public void setDefinedBy(String definedBy) { + this.definedBy = definedBy; + } + + public Endpoint getEndpoint() { + return endpoint; + } + + public void setEndpoint(Endpoint endpoint) { + this.endpoint = endpoint; + } + + public String convertToJasonPayload() throws JsonProcessingException { + + ObjectMapper objectMapper = new ObjectMapper(); + return objectMapper.writeValueAsString(this); + } +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/notification/sender/v1/model/EmailProviderList.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/notification/sender/v1/model/EmailProviderList.java new file mode 100644 index 00000000000..05741cf970c --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/notification/sender/v1/model/EmailProviderList.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.identity.integration.test.rest.api.server.notification.sender.v1.model; + +import java.util.ArrayList; +import java.util.Objects; + +/** + * Email Provider List + */ +public class EmailProviderList extends ArrayList { + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + return super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode()); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EmailProviderList {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/notification/sender/v1/model/EmailSender.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/notification/sender/v1/model/EmailSender.java new file mode 100644 index 00000000000..3c7dcd0ad16 --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/notification/sender/v1/model/EmailSender.java @@ -0,0 +1,246 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.identity.integration.test.rest.api.server.notification.sender.v1.model; + +import com.google.gson.annotations.SerializedName; +import io.swagger.v3.oas.annotations.media.Schema; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +/** + * Email Sender + */ +public class EmailSender { + @SerializedName("name") + private String name = null; + + @SerializedName("smtpServerHost") + private String smtpServerHost = null; + + @SerializedName("smtpPort") + private Integer smtpPort = null; + + @SerializedName("fromAddress") + private String fromAddress = null; + + @SerializedName("userName") + private String userName = null; + + @SerializedName("password") + private String password = null; + + @SerializedName("properties") + private List properties = null; + + public EmailSender name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * + * @return name + **/ + @Schema(example = "EmailPublisher", required = true, description = "") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public EmailSender smtpServerHost(String smtpServerHost) { + this.smtpServerHost = smtpServerHost; + return this; + } + + /** + * Get smtpServerHost + * + * @return smtpServerHost + **/ + @Schema(example = "smtp.gmail.com", description = "") + public String getSmtpServerHost() { + return smtpServerHost; + } + + public void setSmtpServerHost(String smtpServerHost) { + this.smtpServerHost = smtpServerHost; + } + + public EmailSender smtpPort(Integer smtpPort) { + this.smtpPort = smtpPort; + return this; + } + + /** + * Get smtpPort + * + * @return smtpPort + **/ + @Schema(example = "587", description = "") + public Integer getSmtpPort() { + return smtpPort; + } + + public void setSmtpPort(Integer smtpPort) { + this.smtpPort = smtpPort; + } + + public EmailSender fromAddress(String fromAddress) { + this.fromAddress = fromAddress; + return this; + } + + /** + * Get fromAddress + * + * @return fromAddress + **/ + @Schema(example = "iam@gmail.com", required = true, description = "") + public String getFromAddress() { + return fromAddress; + } + + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + + public EmailSender userName(String userName) { + this.userName = userName; + return this; + } + + /** + * Get userName + * + * @return userName + **/ + @Schema(example = "iam", description = "") + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public EmailSender password(String password) { + this.password = password; + return this; + } + + /** + * Get password + * + * @return password + **/ + @Schema(example = "iam123", description = "") + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public EmailSender properties(List properties) { + this.properties = properties; + return this; + } + + public EmailSender addPropertiesItem(Properties propertiesItem) { + if (this.properties == null) { + this.properties = new ArrayList(); + } + this.properties.add(propertiesItem); + return this; + } + + /** + * Get properties + * + * @return properties + **/ + @Schema(example = "[{\"key\":\"mail.smtp.starttls.enable\",\"value\":true}]", description = "") + public List getProperties() { + return properties; + } + + public void setProperties(List properties) { + this.properties = properties; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EmailSender emailSender = (EmailSender) o; + return Objects.equals(this.name, emailSender.name) && + Objects.equals(this.smtpServerHost, emailSender.smtpServerHost) && + Objects.equals(this.smtpPort, emailSender.smtpPort) && + Objects.equals(this.fromAddress, emailSender.fromAddress) && + Objects.equals(this.userName, emailSender.userName) && + Objects.equals(this.password, emailSender.password) && + Objects.equals(this.properties, emailSender.properties); + } + + @Override + public int hashCode() { + return Objects.hash(name, smtpServerHost, smtpPort, fromAddress, userName, password, properties); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EmailSender {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" smtpServerHost: ").append(toIndentedString(smtpServerHost)).append("\n"); + sb.append(" smtpPort: ").append(toIndentedString(smtpPort)).append("\n"); + sb.append(" fromAddress: ").append(toIndentedString(fromAddress)).append("\n"); + sb.append(" userName: ").append(toIndentedString(userName)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" properties: ").append(toIndentedString(properties)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/notification/sender/v1/model/EmailSenderAdd.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/notification/sender/v1/model/EmailSenderAdd.java new file mode 100644 index 00000000000..c02b6025295 --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/notification/sender/v1/model/EmailSenderAdd.java @@ -0,0 +1,246 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.identity.integration.test.rest.api.server.notification.sender.v1.model; + +import com.google.gson.annotations.SerializedName; +import io.swagger.v3.oas.annotations.media.Schema; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +/** + * Email Sender Add request + */ +public class EmailSenderAdd { + @SerializedName("name") + private String name = null; + + @SerializedName("smtpServerHost") + private String smtpServerHost = null; + + @SerializedName("smtpPort") + private Integer smtpPort = null; + + @SerializedName("fromAddress") + private String fromAddress = null; + + @SerializedName("userName") + private String userName = null; + + @SerializedName("password") + private String password = null; + + @SerializedName("properties") + private List properties = null; + + public EmailSenderAdd name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * + * @return name + **/ + @Schema(description = "") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public EmailSenderAdd smtpServerHost(String smtpServerHost) { + this.smtpServerHost = smtpServerHost; + return this; + } + + /** + * Get smtpServerHost + * + * @return smtpServerHost + **/ + @Schema(description = "") + public String getSmtpServerHost() { + return smtpServerHost; + } + + public void setSmtpServerHost(String smtpServerHost) { + this.smtpServerHost = smtpServerHost; + } + + public EmailSenderAdd smtpPort(Integer smtpPort) { + this.smtpPort = smtpPort; + return this; + } + + /** + * Get smtpPort + * + * @return smtpPort + **/ + @Schema(description = "") + public Integer getSmtpPort() { + return smtpPort; + } + + public void setSmtpPort(Integer smtpPort) { + this.smtpPort = smtpPort; + } + + public EmailSenderAdd fromAddress(String fromAddress) { + this.fromAddress = fromAddress; + return this; + } + + /** + * Get fromAddress + * + * @return fromAddress + **/ + @Schema(example = "iam@gmail.com", required = true, description = "") + public String getFromAddress() { + return fromAddress; + } + + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + + public EmailSenderAdd userName(String userName) { + this.userName = userName; + return this; + } + + /** + * Get userName + * + * @return userName + **/ + @Schema(example = "iam", description = "") + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public EmailSenderAdd password(String password) { + this.password = password; + return this; + } + + /** + * Get password + * + * @return password + **/ + @Schema(example = "iam123", description = "") + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public EmailSenderAdd properties(List properties) { + this.properties = properties; + return this; + } + + public EmailSenderAdd addPropertiesItem(Properties propertiesItem) { + if (this.properties == null) { + this.properties = new ArrayList(); + } + this.properties.add(propertiesItem); + return this; + } + + /** + * Get properties + * + * @return properties + **/ + @Schema(example = "[{\"key\":\"body.scope\",\"value\":\"true\"},{\"key\":\"mail.smtp.starttls.enable\",\"value\":true}]", description = "") + public List getProperties() { + return properties; + } + + public void setProperties(List properties) { + this.properties = properties; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EmailSenderAdd emailSenderAdd = (EmailSenderAdd) o; + return Objects.equals(this.name, emailSenderAdd.name) && + Objects.equals(this.smtpServerHost, emailSenderAdd.smtpServerHost) && + Objects.equals(this.smtpPort, emailSenderAdd.smtpPort) && + Objects.equals(this.fromAddress, emailSenderAdd.fromAddress) && + Objects.equals(this.userName, emailSenderAdd.userName) && + Objects.equals(this.password, emailSenderAdd.password) && + Objects.equals(this.properties, emailSenderAdd.properties); + } + + @Override + public int hashCode() { + return Objects.hash(name, smtpServerHost, smtpPort, fromAddress, userName, password, properties); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EmailSenderAdd {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" smtpServerHost: ").append(toIndentedString(smtpServerHost)).append("\n"); + sb.append(" smtpPort: ").append(toIndentedString(smtpPort)).append("\n"); + sb.append(" fromAddress: ").append(toIndentedString(fromAddress)).append("\n"); + sb.append(" userName: ").append(toIndentedString(userName)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" properties: ").append(toIndentedString(properties)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/notification/sender/v1/model/EmailSenderUpdateRequest.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/notification/sender/v1/model/EmailSenderUpdateRequest.java new file mode 100644 index 00000000000..09ee4d83f5d --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/notification/sender/v1/model/EmailSenderUpdateRequest.java @@ -0,0 +1,222 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.identity.integration.test.rest.api.server.notification.sender.v1.model; + +import com.google.gson.annotations.SerializedName; +import io.swagger.v3.oas.annotations.media.Schema; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +/** + * Email Sender Update Request + */ +public class EmailSenderUpdateRequest { + @SerializedName("smtpServerHost") + private String smtpServerHost = null; + + @SerializedName("smtpPort") + private Integer smtpPort = null; + + @SerializedName("fromAddress") + private String fromAddress = null; + + @SerializedName("userName") + private String userName = null; + + @SerializedName("password") + private String password = null; + + @SerializedName("properties") + private List properties = null; + + public EmailSenderUpdateRequest smtpServerHost(String smtpServerHost) { + this.smtpServerHost = smtpServerHost; + return this; + } + + /** + * Get smtpServerHost + * + * @return smtpServerHost + **/ + @Schema(example = "smtp.gmail.com", description = "") + public String getSmtpServerHost() { + return smtpServerHost; + } + + public void setSmtpServerHost(String smtpServerHost) { + this.smtpServerHost = smtpServerHost; + } + + public EmailSenderUpdateRequest smtpPort(Integer smtpPort) { + this.smtpPort = smtpPort; + return this; + } + + /** + * Get smtpPort + * + * @return smtpPort + **/ + @Schema(example = "587", description = "") + public Integer getSmtpPort() { + return smtpPort; + } + + public void setSmtpPort(Integer smtpPort) { + this.smtpPort = smtpPort; + } + + public EmailSenderUpdateRequest fromAddress(String fromAddress) { + this.fromAddress = fromAddress; + return this; + } + + /** + * Get fromAddress + * + * @return fromAddress + **/ + @Schema(example = "iam@gmail.com", required = true, description = "") + public String getFromAddress() { + return fromAddress; + } + + public void setFromAddress(String fromAddress) { + this.fromAddress = fromAddress; + } + + public EmailSenderUpdateRequest userName(String userName) { + this.userName = userName; + return this; + } + + /** + * Get userName + * + * @return userName + **/ + @Schema(example = "iam", description = "") + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public EmailSenderUpdateRequest password(String password) { + this.password = password; + return this; + } + + /** + * Get password + * + * @return password + **/ + @Schema(example = "iam123", description = "") + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public EmailSenderUpdateRequest properties(List properties) { + this.properties = properties; + return this; + } + + public EmailSenderUpdateRequest addPropertiesItem(Properties propertiesItem) { + if (this.properties == null) { + this.properties = new ArrayList(); + } + this.properties.add(propertiesItem); + return this; + } + + /** + * Get properties + * + * @return properties + **/ + @Schema(example = "[{\"key\":\"body.scope\",\"value\":\"true\"},{\"key\":\"mail.smtp.starttls.enable\",\"value\":true}]", description = "") + public List getProperties() { + return properties; + } + + public void setProperties(List properties) { + this.properties = properties; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EmailSenderUpdateRequest emailSenderUpdateRequest = (EmailSenderUpdateRequest) o; + return Objects.equals(this.smtpServerHost, emailSenderUpdateRequest.smtpServerHost) && + Objects.equals(this.smtpPort, emailSenderUpdateRequest.smtpPort) && + Objects.equals(this.fromAddress, emailSenderUpdateRequest.fromAddress) && + Objects.equals(this.userName, emailSenderUpdateRequest.userName) && + Objects.equals(this.password, emailSenderUpdateRequest.password) && + Objects.equals(this.properties, emailSenderUpdateRequest.properties); + } + + @Override + public int hashCode() { + return Objects.hash(smtpServerHost, smtpPort, fromAddress, userName, password, properties); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EmailSenderUpdateRequest {\n"); + + sb.append(" smtpServerHost: ").append(toIndentedString(smtpServerHost)).append("\n"); + sb.append(" smtpPort: ").append(toIndentedString(smtpPort)).append("\n"); + sb.append(" fromAddress: ").append(toIndentedString(fromAddress)).append("\n"); + sb.append(" userName: ").append(toIndentedString(userName)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" properties: ").append(toIndentedString(properties)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/notification/sender/v1/model/Error.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/notification/sender/v1/model/Error.java new file mode 100644 index 00000000000..079c6219e74 --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/notification/sender/v1/model/Error.java @@ -0,0 +1,164 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.identity.integration.test.rest.api.server.notification.sender.v1.model; + +import com.google.gson.annotations.SerializedName; +import io.swagger.v3.oas.annotations.media.Schema; + +import java.util.Objects; + +/** + * Error + */ +public class Error { + @SerializedName("code") + private String code = null; + + @SerializedName("message") + private String message = null; + + @SerializedName("description") + private String description = null; + + @SerializedName("traceId") + private String traceId = null; + + public Error code(String code) { + this.code = code; + return this; + } + + /** + * Get code + * + * @return code + **/ + @Schema(example = "NSM-00000", description = "") + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public Error message(String message) { + this.message = message; + return this; + } + + /** + * Get message + * + * @return message + **/ + @Schema(example = "Some Error Message", description = "") + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public Error description(String description) { + this.description = description; + return this; + } + + /** + * Get description + * + * @return description + **/ + @Schema(example = "Some Error Description", description = "") + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Error traceId(String traceId) { + this.traceId = traceId; + return this; + } + + /** + * Get traceId + * + * @return traceId + **/ + @Schema(example = "e0fbcfeb-3617-43c4-8dd0-7b7d38e13047", description = "") + public String getTraceId() { + return traceId; + } + + public void setTraceId(String traceId) { + this.traceId = traceId; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Error error = (Error) o; + return Objects.equals(this.code, error.code) && + Objects.equals(this.message, error.message) && + Objects.equals(this.description, error.description) && + Objects.equals(this.traceId, error.traceId); + } + + @Override + public int hashCode() { + return Objects.hash(code, message, description, traceId); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Error {\n"); + + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append(" description: ").append(toIndentedString(description)).append("\n"); + sb.append(" traceId: ").append(toIndentedString(traceId)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/notification/sender/v1/model/Properties.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/notification/sender/v1/model/Properties.java new file mode 100644 index 00000000000..ee86bc29538 --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/notification/sender/v1/model/Properties.java @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.identity.integration.test.rest.api.server.notification.sender.v1.model; + +import com.google.gson.annotations.SerializedName; +import io.swagger.v3.oas.annotations.media.Schema; + +import java.util.Objects; + +/** + * Properties + */ +public class Properties { + @SerializedName("key") + private String key = null; + + @SerializedName("value") + private String value = null; + + public Properties key(String key) { + this.key = key; + return this; + } + + /** + * Get key + * + * @return key + **/ + @Schema(required = true, description = "") + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public Properties value(String value) { + this.value = value; + return this; + } + + /** + * Get value + * + * @return value + **/ + @Schema(required = true, description = "") + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Properties properties = (Properties) o; + return Objects.equals(this.key, properties.key) && + Objects.equals(this.value, properties.value); + } + + @Override + public int hashCode() { + return Objects.hash(key, value); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Properties {\n"); + + sb.append(" key: ").append(toIndentedString(key)).append("\n"); + sb.append(" value: ").append(toIndentedString(value)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/notification/sender/v1/model/SMSProviderList.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/notification/sender/v1/model/SMSProviderList.java new file mode 100644 index 00000000000..92f74ac24f4 --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/notification/sender/v1/model/SMSProviderList.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.identity.integration.test.rest.api.server.notification.sender.v1.model; + +import java.util.ArrayList; +import java.util.Objects; + +/** + * SMS Provider List + */ +public class SMSProviderList extends ArrayList { + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + return super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode()); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SMSProviderList {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/notification/sender/v1/model/SMSSender.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/notification/sender/v1/model/SMSSender.java new file mode 100644 index 00000000000..db94e4a166f --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/notification/sender/v1/model/SMSSender.java @@ -0,0 +1,323 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.identity.integration.test.rest.api.server.notification.sender.v1.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.v3.oas.annotations.media.Schema; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +/** + * SMS Sender + */ +public class SMSSender { + @SerializedName("name") + private String name = null; + + @SerializedName("provider") + private String provider = null; + + @SerializedName("providerURL") + private String providerURL = null; + + @SerializedName("key") + private String key = null; + + @SerializedName("secret") + private String secret = null; + + @SerializedName("sender") + private String sender = null; + + /** + * Gets or Sets contentType + */ + @JsonAdapter(ContentTypeEnum.Adapter.class) + public enum ContentTypeEnum { + @SerializedName("JSON") + JSON("JSON"), + @SerializedName("FORM") + FORM("FORM"); + + private String value; + + ContentTypeEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static ContentTypeEnum fromValue(String input) { + for (ContentTypeEnum b : ContentTypeEnum.values()) { + if (b.value.equals(input)) { + return b; + } + } + return null; + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final ContentTypeEnum enumeration) throws IOException { + jsonWriter.value(String.valueOf(enumeration.getValue())); + } + + @Override + public ContentTypeEnum read(final JsonReader jsonReader) throws IOException { + Object value = jsonReader.nextString(); + return ContentTypeEnum.fromValue((String) (value)); + } + } + } + + @SerializedName("contentType") + private ContentTypeEnum contentType = null; + + @SerializedName("properties") + private List properties = null; + + public SMSSender name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * + * @return name + **/ + @Schema(example = "SMSPublisher", required = true, description = "") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public SMSSender provider(String provider) { + this.provider = provider; + return this; + } + + /** + * Get provider + * + * @return provider + **/ + @Schema(example = "NEXMO", required = true, description = "") + public String getProvider() { + return provider; + } + + public void setProvider(String provider) { + this.provider = provider; + } + + public SMSSender providerURL(String providerURL) { + this.providerURL = providerURL; + return this; + } + + /** + * Get providerURL + * + * @return providerURL + **/ + @Schema(example = "https://rest.nexmo.com/sms/json", required = true, description = "") + public String getProviderURL() { + return providerURL; + } + + public void setProviderURL(String providerURL) { + this.providerURL = providerURL; + } + + public SMSSender key(String key) { + this.key = key; + return this; + } + + /** + * Get key + * + * @return key + **/ + @Schema(example = "123**45", description = "") + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public SMSSender secret(String secret) { + this.secret = secret; + return this; + } + + /** + * Get secret + * + * @return secret + **/ + @Schema(example = "5tg**ssd", description = "") + public String getSecret() { + return secret; + } + + public void setSecret(String secret) { + this.secret = secret; + } + + public SMSSender sender(String sender) { + this.sender = sender; + return this; + } + + /** + * Get sender + * + * @return sender + **/ + @Schema(example = "+94 775563324", description = "") + public String getSender() { + return sender; + } + + public void setSender(String sender) { + this.sender = sender; + } + + public SMSSender contentType(ContentTypeEnum contentType) { + this.contentType = contentType; + return this; + } + + /** + * Get contentType + * + * @return contentType + **/ + @Schema(required = true, description = "") + public ContentTypeEnum getContentType() { + return contentType; + } + + public void setContentType(ContentTypeEnum contentType) { + this.contentType = contentType; + } + + public SMSSender properties(List properties) { + this.properties = properties; + return this; + } + + public SMSSender addPropertiesItem(Properties propertiesItem) { + if (this.properties == null) { + this.properties = new ArrayList(); + } + this.properties.add(propertiesItem); + return this; + } + + /** + * Get properties + * + * @return properties + **/ + @Schema(example = "[{\"key\":\"body.scope\",\"value\":\"internal\"},{\"key\":\"http.headers\",\"value\":\"X-Version: 1, Authorization: bearer ,Accept: application/json ,Content-Type: application/json\"}]", description = "") + public List getProperties() { + return properties; + } + + public void setProperties(List properties) { + this.properties = properties; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SMSSender smSSender = (SMSSender) o; + return Objects.equals(this.name, smSSender.name) && + Objects.equals(this.provider, smSSender.provider) && + Objects.equals(this.providerURL, smSSender.providerURL) && + Objects.equals(this.key, smSSender.key) && + Objects.equals(this.secret, smSSender.secret) && + Objects.equals(this.sender, smSSender.sender) && + Objects.equals(this.contentType, smSSender.contentType) && + Objects.equals(this.properties, smSSender.properties); + } + + @Override + public int hashCode() { + return Objects.hash(name, provider, providerURL, key, secret, sender, contentType, properties); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SMSSender {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" provider: ").append(toIndentedString(provider)).append("\n"); + sb.append(" providerURL: ").append(toIndentedString(providerURL)).append("\n"); + sb.append(" key: ").append(toIndentedString(key)).append("\n"); + sb.append(" secret: ").append(toIndentedString(secret)).append("\n"); + sb.append(" sender: ").append(toIndentedString(sender)).append("\n"); + sb.append(" contentType: ").append(toIndentedString(contentType)).append("\n"); + sb.append(" properties: ").append(toIndentedString(properties)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/notification/sender/v1/model/SMSSenderAdd.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/notification/sender/v1/model/SMSSenderAdd.java new file mode 100644 index 00000000000..41c6c3dc878 --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/notification/sender/v1/model/SMSSenderAdd.java @@ -0,0 +1,323 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.identity.integration.test.rest.api.server.notification.sender.v1.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.v3.oas.annotations.media.Schema; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +/** + * SMS Sender Add request + */ +public class SMSSenderAdd { + @SerializedName("name") + private String name = null; + + @SerializedName("provider") + private String provider = null; + + @SerializedName("providerURL") + private String providerURL = null; + + @SerializedName("key") + private String key = null; + + @SerializedName("secret") + private String secret = null; + + @SerializedName("sender") + private String sender = null; + + /** + * Gets or Sets contentType + */ + @JsonAdapter(ContentTypeEnum.Adapter.class) + public enum ContentTypeEnum { + @SerializedName("JSON") + JSON("JSON"), + @SerializedName("FORM") + FORM("FORM"); + + private String value; + + ContentTypeEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static ContentTypeEnum fromValue(String input) { + for (ContentTypeEnum b : ContentTypeEnum.values()) { + if (b.value.equals(input)) { + return b; + } + } + return null; + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final ContentTypeEnum enumeration) throws IOException { + jsonWriter.value(String.valueOf(enumeration.getValue())); + } + + @Override + public ContentTypeEnum read(final JsonReader jsonReader) throws IOException { + Object value = jsonReader.nextString(); + return ContentTypeEnum.fromValue((String) (value)); + } + } + } + + @SerializedName("contentType") + private ContentTypeEnum contentType = null; + + @SerializedName("properties") + private List properties = null; + + public SMSSenderAdd name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * + * @return name + **/ + @Schema(example = "SMSPublisher", description = "") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public SMSSenderAdd provider(String provider) { + this.provider = provider; + return this; + } + + /** + * Get provider + * + * @return provider + **/ + @Schema(example = "NEXMO", required = true, description = "") + public String getProvider() { + return provider; + } + + public void setProvider(String provider) { + this.provider = provider; + } + + public SMSSenderAdd providerURL(String providerURL) { + this.providerURL = providerURL; + return this; + } + + /** + * Get providerURL + * + * @return providerURL + **/ + @Schema(example = "https://rest.nexmo.com/sms/json", required = true, description = "") + public String getProviderURL() { + return providerURL; + } + + public void setProviderURL(String providerURL) { + this.providerURL = providerURL; + } + + public SMSSenderAdd key(String key) { + this.key = key; + return this; + } + + /** + * Get key + * + * @return key + **/ + @Schema(example = "123**45", description = "") + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public SMSSenderAdd secret(String secret) { + this.secret = secret; + return this; + } + + /** + * Get secret + * + * @return secret + **/ + @Schema(example = "5tg**ssd", description = "") + public String getSecret() { + return secret; + } + + public void setSecret(String secret) { + this.secret = secret; + } + + public SMSSenderAdd sender(String sender) { + this.sender = sender; + return this; + } + + /** + * Get sender + * + * @return sender + **/ + @Schema(example = "+94 775563324", description = "") + public String getSender() { + return sender; + } + + public void setSender(String sender) { + this.sender = sender; + } + + public SMSSenderAdd contentType(ContentTypeEnum contentType) { + this.contentType = contentType; + return this; + } + + /** + * Get contentType + * + * @return contentType + **/ + @Schema(required = true, description = "") + public ContentTypeEnum getContentType() { + return contentType; + } + + public void setContentType(ContentTypeEnum contentType) { + this.contentType = contentType; + } + + public SMSSenderAdd properties(List properties) { + this.properties = properties; + return this; + } + + public SMSSenderAdd addPropertiesItem(Properties propertiesItem) { + if (this.properties == null) { + this.properties = new ArrayList(); + } + this.properties.add(propertiesItem); + return this; + } + + /** + * Get properties + * + * @return properties + **/ + @Schema(example = "[{\"key\":\"http.headers\",\"value\":\"X-Version: 1, Authorization: bearer ,Accept: application/json ,Content-Type: application/json\"}]", description = "") + public List getProperties() { + return properties; + } + + public void setProperties(List properties) { + this.properties = properties; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SMSSenderAdd smSSenderAdd = (SMSSenderAdd) o; + return Objects.equals(this.name, smSSenderAdd.name) && + Objects.equals(this.provider, smSSenderAdd.provider) && + Objects.equals(this.providerURL, smSSenderAdd.providerURL) && + Objects.equals(this.key, smSSenderAdd.key) && + Objects.equals(this.secret, smSSenderAdd.secret) && + Objects.equals(this.sender, smSSenderAdd.sender) && + Objects.equals(this.contentType, smSSenderAdd.contentType) && + Objects.equals(this.properties, smSSenderAdd.properties); + } + + @Override + public int hashCode() { + return Objects.hash(name, provider, providerURL, key, secret, sender, contentType, properties); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SMSSenderAdd {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" provider: ").append(toIndentedString(provider)).append("\n"); + sb.append(" providerURL: ").append(toIndentedString(providerURL)).append("\n"); + sb.append(" key: ").append(toIndentedString(key)).append("\n"); + sb.append(" secret: ").append(toIndentedString(secret)).append("\n"); + sb.append(" sender: ").append(toIndentedString(sender)).append("\n"); + sb.append(" contentType: ").append(toIndentedString(contentType)).append("\n"); + sb.append(" properties: ").append(toIndentedString(properties)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/notification/sender/v1/model/SMSSenderUpdateRequest.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/notification/sender/v1/model/SMSSenderUpdateRequest.java new file mode 100644 index 00000000000..7c00e18e727 --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/notification/sender/v1/model/SMSSenderUpdateRequest.java @@ -0,0 +1,299 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.identity.integration.test.rest.api.server.notification.sender.v1.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.v3.oas.annotations.media.Schema; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +/** + * SMS Sender Update Request + */ +public class SMSSenderUpdateRequest { + @SerializedName("provider") + private String provider = null; + + @SerializedName("providerURL") + private String providerURL = null; + + @SerializedName("key") + private String key = null; + + @SerializedName("secret") + private String secret = null; + + @SerializedName("sender") + private String sender = null; + + /** + * Gets or Sets contentType + */ + @JsonAdapter(ContentTypeEnum.Adapter.class) + public enum ContentTypeEnum { + @SerializedName("JSON") + JSON("JSON"), + @SerializedName("FORM") + FORM("FORM"); + + private String value; + + ContentTypeEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static ContentTypeEnum fromValue(String input) { + for (ContentTypeEnum b : ContentTypeEnum.values()) { + if (b.value.equals(input)) { + return b; + } + } + return null; + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final ContentTypeEnum enumeration) throws IOException { + jsonWriter.value(String.valueOf(enumeration.getValue())); + } + + @Override + public ContentTypeEnum read(final JsonReader jsonReader) throws IOException { + Object value = jsonReader.nextString(); + return ContentTypeEnum.fromValue((String) (value)); + } + } + } + + @SerializedName("contentType") + private ContentTypeEnum contentType = null; + + @SerializedName("properties") + private List properties = null; + + public SMSSenderUpdateRequest provider(String provider) { + this.provider = provider; + return this; + } + + /** + * Get provider + * + * @return provider + **/ + @Schema(example = "NEXMO", required = true, description = "") + public String getProvider() { + return provider; + } + + public void setProvider(String provider) { + this.provider = provider; + } + + public SMSSenderUpdateRequest providerURL(String providerURL) { + this.providerURL = providerURL; + return this; + } + + /** + * Get providerURL + * + * @return providerURL + **/ + @Schema(example = "https://rest.nexmo.com/sms/json", required = true, description = "") + public String getProviderURL() { + return providerURL; + } + + public void setProviderURL(String providerURL) { + this.providerURL = providerURL; + } + + public SMSSenderUpdateRequest key(String key) { + this.key = key; + return this; + } + + /** + * Get key + * + * @return key + **/ + @Schema(example = "123**45", description = "") + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public SMSSenderUpdateRequest secret(String secret) { + this.secret = secret; + return this; + } + + /** + * Get secret + * + * @return secret + **/ + @Schema(example = "5tg**ssd", description = "") + public String getSecret() { + return secret; + } + + public void setSecret(String secret) { + this.secret = secret; + } + + public SMSSenderUpdateRequest sender(String sender) { + this.sender = sender; + return this; + } + + /** + * Get sender + * + * @return sender + **/ + @Schema(example = "+94 775563324", description = "") + public String getSender() { + return sender; + } + + public void setSender(String sender) { + this.sender = sender; + } + + public SMSSenderUpdateRequest contentType(ContentTypeEnum contentType) { + this.contentType = contentType; + return this; + } + + /** + * Get contentType + * + * @return contentType + **/ + @Schema(required = true, description = "") + public ContentTypeEnum getContentType() { + return contentType; + } + + public void setContentType(ContentTypeEnum contentType) { + this.contentType = contentType; + } + + public SMSSenderUpdateRequest properties(List properties) { + this.properties = properties; + return this; + } + + public SMSSenderUpdateRequest addPropertiesItem(Properties propertiesItem) { + if (this.properties == null) { + this.properties = new ArrayList(); + } + this.properties.add(propertiesItem); + return this; + } + + /** + * Get properties + * + * @return properties + **/ + @Schema(example = "[{\"key\":\"http.headers\",\"value\":\"X-Version: 1, Authorization: bearer ,Accept: application/json ,Content-Type: application/json\"}]", description = "") + public List getProperties() { + return properties; + } + + public void setProperties(List properties) { + this.properties = properties; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SMSSenderUpdateRequest smSSenderUpdateRequest = (SMSSenderUpdateRequest) o; + return Objects.equals(this.provider, smSSenderUpdateRequest.provider) && + Objects.equals(this.providerURL, smSSenderUpdateRequest.providerURL) && + Objects.equals(this.key, smSSenderUpdateRequest.key) && + Objects.equals(this.secret, smSSenderUpdateRequest.secret) && + Objects.equals(this.sender, smSSenderUpdateRequest.sender) && + Objects.equals(this.contentType, smSSenderUpdateRequest.contentType) && + Objects.equals(this.properties, smSSenderUpdateRequest.properties); + } + + @Override + public int hashCode() { + return Objects.hash(provider, providerURL, key, secret, sender, contentType, properties); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SMSSenderUpdateRequest {\n"); + + sb.append(" provider: ").append(toIndentedString(provider)).append("\n"); + sb.append(" providerURL: ").append(toIndentedString(providerURL)).append("\n"); + sb.append(" key: ").append(toIndentedString(key)).append("\n"); + sb.append(" secret: ").append(toIndentedString(secret)).append("\n"); + sb.append(" sender: ").append(toIndentedString(sender)).append("\n"); + sb.append(" contentType: ").append(toIndentedString(contentType)).append("\n"); + sb.append(" properties: ").append(toIndentedString(properties)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/organization/management/v1/OrganizationManagementFailureTest.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/organization/management/v1/OrganizationManagementFailureTest.java index 6922e738930..203f0b7967a 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/organization/management/v1/OrganizationManagementFailureTest.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/organization/management/v1/OrganizationManagementFailureTest.java @@ -540,32 +540,6 @@ public void testGetPaginatedOrganizationsDiscoveryWithInvalidLimitAndOffset(Stri validateErrorResponse(response, HttpStatus.SC_BAD_REQUEST, ERROR_CODE_BAD_REQUEST); } - /* - * TODO: After the issue https://github.com/wso2/product-is/issues/21025 is fixed, - * remove the method testGetPaginatedOrganizationsDiscoveryWithInvalidOffsetAndLimitZero - * along with its data provider organizationDiscoveryInvalidOffsetAtLimitAndLimitZeroDataProvider. - */ - @DataProvider(name = "organizationDiscoveryInvalidOffsetAtLimitAndLimitZeroDataProvider") - public Object[][] organizationDiscoveryInvalidOffsetAtLimitAndLimitZeroDataProvider() { - - return new Object[][]{ - {"20", "0"}, - {"25", "0"} - }; - } - - @Test(dependsOnMethods = "testGetPaginatedOrganizationsDiscoveryWithInvalidLimitAndOffset", - dataProvider = "organizationDiscoveryInvalidOffsetAtLimitAndLimitZeroDataProvider") - public void testGetPaginatedOrganizationsDiscoveryWithInvalidOffsetAndLimitZero(String offset, - String limit) { - - String url = ORGANIZATION_MANAGEMENT_API_BASE_PATH + ORGANIZATION_DISCOVERY_API_PATH + QUESTION_MARK + - OFFSET_QUERY_PARAM + EQUAL + offset + AMPERSAND + LIMIT_QUERY_PARAM + EQUAL + limit; - - Response response = getResponseOfGetWithOAuth2(url, m2mToken); - validateErrorResponse(response, HttpStatus.SC_INTERNAL_SERVER_ERROR, ERROR_CODE_SERVER_ERROR); - } - @Test(dependsOnMethods = "testGetPaginatedOrganizationsDiscoveryWithInvalidLimitAndOffset") public void testGetPaginatedMetaAttributesWithInvalidLimit() { diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/organization/management/v1/OrganizationManagementSuccessTest.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/organization/management/v1/OrganizationManagementSuccessTest.java index 92bea4666d9..2c9ccd88d3e 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/organization/management/v1/OrganizationManagementSuccessTest.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/organization/management/v1/OrganizationManagementSuccessTest.java @@ -798,6 +798,32 @@ public void testGetPaginatedOrganizations(int limit) { validateOrganizationsOnPage(previousPageResponse, 1, NUM_OF_ORGANIZATIONS_FOR_PAGINATION_TESTS, limit); } + @DataProvider(name = "organizationDiscoveryInvalidOffsetAtLimitAndLimitZeroDataProvider") + public Object[][] organizationDiscoveryInvalidOffsetAtLimitAndLimitZeroDataProvider() { + + return new Object[][]{ + {"20", "0"}, + {"25", "0"} + }; + } + + @Test(groups = "organizationPaginationTests", + dependsOnMethods = "createOrganizationsForPaginationTests", + dataProvider = "organizationDiscoveryInvalidOffsetAtLimitAndLimitZeroDataProvider") + public void testGetPaginatedOrganizationsDiscoveryWithInvalidOffsetAndLimitZero(String offset, + String limit) { + + String url = ORGANIZATION_MANAGEMENT_API_BASE_PATH + ORGANIZATION_DISCOVERY_API_PATH + QUESTION_MARK + + OFFSET_QUERY_PARAM + EQUAL + offset + AMPERSAND + LIMIT_QUERY_PARAM + EQUAL + limit; + + Response response = getResponseOfGetWithOAuth2(url, m2mToken); + validateHttpStatusCode(response, HttpStatus.SC_OK); + List> returnedOrganizations = response.jsonPath().getList(ORGANIZATIONS_PATH_PARAM); + Assert.assertNull(returnedOrganizations); + int totalResults = response.jsonPath().getInt("totalResults"); + Assert.assertEquals(totalResults, 0, "Total results should be 0 when the limit is 0."); + } + @DataProvider(name = "organizationPaginationNumericEdgeCasesOfLimitDataProvider") public Object[][] organizationPaginationNumericEdgeCasesOfLimitDataProvider() { @@ -806,7 +832,8 @@ public Object[][] organizationPaginationNumericEdgeCasesOfLimitDataProvider() { }; } - @Test(groups = "organizationPaginationTests", dependsOnMethods = "createOrganizationsForPaginationTests", + @Test(groups = "organizationPaginationTests", + dependsOnMethods = "testGetPaginatedOrganizationsDiscoveryWithInvalidOffsetAndLimitZero", dataProvider = "organizationPaginationNumericEdgeCasesOfLimitDataProvider") public void testGetPaginatedOrganizationsForNumericEdgeCasesOfLimit(int limit) { diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/rules/metadata/v1/RulesMetadataFailureTest.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/rules/metadata/v1/RulesMetadataFailureTest.java new file mode 100644 index 00000000000..13219d2fa82 --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/rules/metadata/v1/RulesMetadataFailureTest.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.identity.integration.test.rest.api.server.rules.metadata.v1; + +import io.restassured.RestAssured; +import io.restassured.response.Response; +import org.apache.http.HttpStatus; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; +import org.wso2.carbon.automation.engine.context.TestUserMode; + +import static org.hamcrest.CoreMatchers.equalTo; + +public class RulesMetadataFailureTest extends RulesMetadataTestBase { + + @DataProvider(name = "testExecutionContextProvider") + public static Object[][] getTestExecutionContext() { + + return new Object[][]{ + {TestUserMode.SUPER_TENANT_ADMIN}, + {TestUserMode.TENANT_ADMIN} + }; + } + + @Factory(dataProvider = "testExecutionContextProvider") + public RulesMetadataFailureTest(TestUserMode userMode) throws Exception { + + super.init(userMode); + this.context = isServer; + this.authenticatingUserName = context.getContextTenant().getTenantAdmin().getUserName(); + this.authenticatingCredential = context.getContextTenant().getTenantAdmin().getPassword(); + this.tenant = context.getContextTenant().getDomain(); + } + + @BeforeClass(alwaysRun = true) + public void init() throws Exception { + + super.initTestClass(tenant); + } + + @AfterClass(alwaysRun = true) + public void conclude() { + + super.conclude(); + } + + @BeforeMethod(alwaysRun = true) + public void testInit() { + + RestAssured.basePath = basePath; + } + + @Test + public void testGetRuleMetadataForNotImplementedFlow() throws Exception { + + Response responseOfGet = getResponseOfGet(getAPIRequestForFlow("preLogin")); + responseOfGet.then() + .log().ifValidationFails() + .assertThat() + .statusCode(HttpStatus.SC_BAD_REQUEST) + .body("code", equalTo("RULEMETA-60001")) + .body("message", equalTo("Invalid flow.")) + .body("description", equalTo("Provided flow type is invalid or not implemented.")); + } +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/rules/metadata/v1/RulesMetadataSuccessTest.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/rules/metadata/v1/RulesMetadataSuccessTest.java new file mode 100644 index 00000000000..88633f57f71 --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/rules/metadata/v1/RulesMetadataSuccessTest.java @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.identity.integration.test.rest.api.server.rules.metadata.v1; + +import io.restassured.RestAssured; +import io.restassured.response.Response; +import org.apache.http.HttpStatus; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Factory; +import org.testng.annotations.Test; +import org.wso2.carbon.automation.engine.context.TestUserMode; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.Matchers.hasItems; + +public class RulesMetadataSuccessTest extends RulesMetadataTestBase { + + @DataProvider(name = "testExecutionContextProvider") + public static Object[][] getTestExecutionContext() { + + return new Object[][]{ + {TestUserMode.SUPER_TENANT_ADMIN}, + {TestUserMode.TENANT_ADMIN} + }; + } + + @Factory(dataProvider = "testExecutionContextProvider") + public RulesMetadataSuccessTest(TestUserMode userMode) throws Exception { + + super.init(userMode); + this.context = isServer; + this.authenticatingUserName = context.getContextTenant().getTenantAdmin().getUserName(); + this.authenticatingCredential = context.getContextTenant().getTenantAdmin().getPassword(); + this.tenant = context.getContextTenant().getDomain(); + } + + @BeforeClass(alwaysRun = true) + public void init() throws Exception { + + super.initTestClass(tenant); + } + + @AfterClass(alwaysRun = true) + public void conclude() { + + super.conclude(); + } + + @BeforeMethod(alwaysRun = true) + public void testInit() { + + RestAssured.basePath = basePath; + } + + @DataProvider(name = "flowProvider") + public static Object[][] getFlows() { + + return new Object[][]{ + {"preIssueAccessToken"}, + }; + } + + @Test(dataProvider = "flowProvider") + public void testGetRuleMetadata(String flow) throws Exception { + + Response responseOfGet = getResponseOfGet(getAPIRequestForValidFlow(flow)); + validateResponse(flow, responseOfGet); + } + + private static void validateResponse(String flow, Response response) { + + if (flow.equals("preIssueAccessToken")) { + validateResponseForPreIssueAccessTokenFlow(response); + } else { + throw new IllegalArgumentException("Invalid flow: " + flow); + } + } + + private static void validateResponseForPreIssueAccessTokenFlow(Response response) { + + response.then() + .log().ifValidationFails() + .assertThat() + .statusCode(HttpStatus.SC_OK) + .body("[0].field.name", equalTo("application")) + .body("[0].field.displayName", equalTo("application")) + .body("[0].operators.name", hasItems("equals", "notEquals")) + .body("[0].operators.displayName", hasItems("equals", "not equals")) + .body("[0].value.inputType", equalTo("options")) + .body("[0].value.valueType", equalTo("reference")) + .body("[0].value.valueReferenceAttribute", equalTo("id")) + .body("[0].value.valueDisplayAttribute", equalTo("name")) + .body("[0].value.links.href", + hasItems("/applications?offset=0&limit=10", "/applications?filter=&limit=10")) + .body("[0].value.links.method", hasItems("GET")) + .body("[0].value.links.rel", hasItems("values", "filter")) + .body("[1].field.name", equalTo("grantType")) + .body("[1].field.displayName", equalTo("grant type")) + .body("[1].operators.name", hasItems("equals", "notEquals")) + .body("[1].operators.displayName", hasItems("equals", "not equals")) + .body("[1].value.inputType", equalTo("options")) + .body("[1].value.valueType", equalTo("string")) + .body("[1].value.values.name", + hasItems("authorization_code", "password", "refresh_token", "client_credentials")) + .body("[1].value.values.displayName", + hasItems("authorization code", "password", "refresh token", "client credentials")); + } +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/rules/metadata/v1/RulesMetadataTestBase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/rules/metadata/v1/RulesMetadataTestBase.java new file mode 100644 index 00000000000..6dad1077fd1 --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/server/rules/metadata/v1/RulesMetadataTestBase.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.identity.integration.test.rest.api.server.rules.metadata.v1; + +import org.testng.Assert; +import org.wso2.identity.integration.test.rest.api.server.common.RESTAPIServerTestBase; + +import java.io.IOException; + +public class RulesMetadataTestBase extends RESTAPIServerTestBase { + + private static final String API_DEFINITION_NAME = "rule-metadata.yaml"; + private static final String API_VERSION = "v1"; + + private static String swaggerDefinition; + + static { + String API_PACKAGE_NAME = "org.wso2.carbon.identity.api.server.rule.metadata.v1"; + try { + swaggerDefinition = getAPISwaggerDefinition(API_PACKAGE_NAME, API_DEFINITION_NAME); + } catch (IOException e) { + Assert.fail(String.format("Unable to read the swagger definition %s from %s", API_DEFINITION_NAME, + API_PACKAGE_NAME), e); + } + } + + protected void initTestClass(String tenantDomain) throws IOException { + + super.testInit(API_VERSION, swaggerDefinition, tenantDomain); + } + + protected String getAPIRequestForValidFlow(String flow) { + + validateFlow(flow); + return getAPIEndpoint() + "?flow=" + flow; + } + + protected String getAPIRequestForFlow(String flow) { + + return getAPIEndpoint() + "?flow=" + flow; + } + + protected String getAPIEndpoint() { + + return "/rules/metadata"; + } + + private void validateFlow(String flow) { + + if (!"preIssueAccessToken".equals(flow)) { + throw new IllegalArgumentException("Invalid flow: " + flow); + } + } +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/user/common/model/PhoneNumbers.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/user/common/model/PhoneNumbers.java new file mode 100644 index 00000000000..bd74affd7ef --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/user/common/model/PhoneNumbers.java @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.wso2.identity.integration.test.rest.api.user.common.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModelProperty; + +import javax.validation.Valid; +import java.util.Objects; + +public class PhoneNumbers { + + private String type; + private String value; + + public PhoneNumbers type(String type) { + + this.type = type; + return this; + } + + @ApiModelProperty(example = "mobile") + @JsonProperty("type") + @Valid + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public PhoneNumbers value(String value) { + + this.value = value; + return this; + } + + @ApiModelProperty(example = "1111111111") + @JsonProperty("value") + @Valid + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + @Override + public boolean equals(Object o) { + + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + PhoneNumbers email = (PhoneNumbers) o; + return Objects.equals(this.type, email.type) && + Objects.equals(this.value, email.value); + } + + @Override + public int hashCode() { + return Objects.hash(type, value); + } + + @Override + public String toString() { + + return "class Email {\n" + + " type: " + toIndentedString(type) + "\n" + + " value: " + toIndentedString(value) + "\n" + + "}"; + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + + if (o == null) { + return "null"; + } + return o.toString(); + } +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/user/common/model/UserObject.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/user/common/model/UserObject.java index 843e136e136..ca2963ad363 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/user/common/model/UserObject.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/rest/api/user/common/model/UserObject.java @@ -33,6 +33,7 @@ public class UserObject { private String userName; private String password; private List emails = null; + private List phoneNumbers = null; private String locale; private ScimSchemaExtensionEnterprise scimSchemaExtensionEnterprise; @@ -144,6 +145,31 @@ public UserObject addEmail(Email email) { return this; } + public UserObject phoneNumbers(List phoneNumbers) { + + this.phoneNumbers = phoneNumbers; + return this; + } + + @ApiModelProperty() + @JsonProperty("phoneNumbers") + @Valid + public List getPhoneNumbers() { + return phoneNumbers; + } + + public void setPhoneNumbers(List phoneNumbers) { + this.phoneNumbers = phoneNumbers; + } + + public UserObject addPhoneNumbers(PhoneNumbers phoneNumbers) { + if (this.phoneNumbers == null) { + this.phoneNumbers = new ArrayList<>(); + } + this.phoneNumbers.add(phoneNumbers); + return this; + } + /** * **/ diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/restclients/ClaimManagementRestClient.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/restclients/ClaimManagementRestClient.java index e30a2c84189..8c0ad366665 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/restclients/ClaimManagementRestClient.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/restclients/ClaimManagementRestClient.java @@ -127,6 +127,16 @@ public void updateClaim(String dialectId, String claimId, String requestBody) { "Claim update failed"); } catch (IOException e) { Assert.fail("Error occurred while updating the claim."); + } + + public void updateExternalClaim(String dialectId, String claimId, ExternalClaimReq claimRequest) throws IOException { + + String endPointUrl = serverBasePath + CLAIM_DIALECTS_ENDPOINT_URI + PATH_SEPARATOR + dialectId + + CLAIMS_ENDPOINT_URI + PATH_SEPARATOR + claimId; + String jsonRequest = toJSONString(claimRequest); + try (CloseableHttpResponse response = getResponseOfHttpPut(endPointUrl, jsonRequest, getHeaders())) { + Assert.assertEquals(response.getStatusLine().getStatusCode(), HttpServletResponse.SC_OK, + "External claim update failed"); } } diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/restclients/NotificationSenderRestClient.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/restclients/NotificationSenderRestClient.java new file mode 100644 index 00000000000..e6523008432 --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/restclients/NotificationSenderRestClient.java @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2024, WSO2 LLC. (http://www.wso2.com). + * + * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.wso2.identity.integration.test.restclients; + +import io.restassured.http.ContentType; +import org.apache.commons.codec.binary.Base64; +import org.apache.http.Header; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.message.BasicHeader; +import org.testng.Assert; +import org.wso2.carbon.automation.engine.context.beans.Tenant; +import org.wso2.carbon.utils.multitenancy.MultitenantConstants; +import org.wso2.identity.integration.test.rest.api.server.notification.sender.v1.model.SMSSender; +import org.wso2.identity.integration.test.utils.OAuth2Constant; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +/** + * Rest client for Notification Sender configurations. + */ +public class NotificationSenderRestClient extends RestBaseClient { + + private static final String NOTIFICATION_SENDER_SMS_ENDPOINT = "api/server/v1/notification-senders/sms"; + private final String serverUrl; + private final String tenantDomain; + private final String username; + private final String password; + + public NotificationSenderRestClient(String serverUrl, Tenant tenantInfo) { + + this.serverUrl = serverUrl; + this.tenantDomain = tenantInfo.getContextUser().getUserDomain(); + this.username = tenantInfo.getContextUser().getUserName(); + this.password = tenantInfo.getContextUser().getPassword(); + } + + /** + * Create SMS Sender. + * + * @param smsSender SMS sender details. + * @throws Exception If an error occurred while creating the SMS sender. + */ + public void createSMSProvider(SMSSender smsSender) throws Exception { + + String jsonRequest = toJSONString(smsSender); + + try (CloseableHttpResponse response = getResponseOfHttpPost(getSMSSenderPath(), jsonRequest, getHeaders())) { + Assert.assertEquals(response.getStatusLine().getStatusCode(), HttpServletResponse.SC_CREATED, + "Notification sender creation failed"); + } + } + + /** + * Delete SMS Sender. + * + * @throws Exception If an error occurred while creating the SMS sender. + */ + public void deleteSMSProvider() throws Exception { + + try (CloseableHttpResponse response = getResponseOfHttpDelete(getSMSSenderPath() + "/SMSPublisher", + getHeaders())) { + Assert.assertEquals(response.getStatusLine().getStatusCode(), HttpServletResponse.SC_NO_CONTENT, + "Notification sender deletion failed"); + } + } + + private Header[] getHeaders() { + + Header[] headerList = new Header[3]; + headerList[0] = new BasicHeader(USER_AGENT_ATTRIBUTE, OAuth2Constant.USER_AGENT); + headerList[1] = new BasicHeader(AUTHORIZATION_ATTRIBUTE, BASIC_AUTHORIZATION_ATTRIBUTE + + Base64.encodeBase64String((username + ":" + password).getBytes()).trim()); + headerList[2] = new BasicHeader(CONTENT_TYPE_ATTRIBUTE, String.valueOf(ContentType.JSON)); + + return headerList; + } + + private String getSMSSenderPath() { + + if (tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { + return serverUrl + NOTIFICATION_SENDER_SMS_ENDPOINT; + } else { + return serverUrl + TENANT_PATH + tenantDomain + PATH_SEPARATOR + NOTIFICATION_SENDER_SMS_ENDPOINT; + } + } + + /** + * Close the HTTP client. + * + * @throws IOException If an error occurred while closing the Http Client. + */ + public void closeHttpClient() throws IOException { + + client.close(); + } +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/scim2/SCIM2UserTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/scim2/SCIM2UserTestCase.java index df7f584a172..c1e3dfddc7a 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/scim2/SCIM2UserTestCase.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/scim2/SCIM2UserTestCase.java @@ -380,75 +380,6 @@ public void testGetResourceTypes() throws Exception { } - @Test(dependsOnMethods = "testGetUser") - public void testUpdateUserWhenExternalClaimDeleted() throws Exception { - - AutomationContext context = new AutomationContext("IDENTITY", testUserMode); - backendURL = context.getContextUrls().getBackEndUrl(); - loginLogoutClient = new LoginLogoutClient(context); - sessionCookie = loginLogoutClient.login(); - HttpPost postRequest = new HttpPost(getPath()); - postRequest.addHeader(HttpHeaders.AUTHORIZATION, getAuthzHeader()); - postRequest.addHeader(HttpHeaders.CONTENT_TYPE, "application/json"); - - JSONObject rootObject = new JSONObject(); - - JSONArray schemas = new JSONArray(); - rootObject.put(SCHEMAS_ATTRIBUTE, schemas); - - JSONObject names = new JSONObject(); - names.put(FAMILY_NAME_ATTRIBUTE, "udaranga"); - names.put(GIVEN_NAME_ATTRIBUTE, "buddhima"); - - rootObject.put(NAME_ATTRIBUTE, names); - rootObject.put(USER_NAME_ATTRIBUTE, "wso2is"); - - JSONObject emailWork = new JSONObject(); - emailWork.put(TYPE_PARAM, EMAIL_TYPE_WORK_ATTRIBUTE); - emailWork.put(VALUE_PARAM, EMAIL_TYPE_WORK_CLAIM_VALUE); - - JSONObject emailHome = new JSONObject(); - emailHome.put(TYPE_PARAM, EMAIL_TYPE_HOME_ATTRIBUTE); - emailHome.put(VALUE_PARAM, EMAIL_TYPE_HOME_CLAIM_VALUE); - - JSONArray emails = new JSONArray(); - emails.add(emailWork); - emails.add(emailHome); - - rootObject.put(EMAILS_ATTRIBUTE, emails); - - rootObject.put(PASSWORD_ATTRIBUTE, PASSWORD); - - StringEntity entity = new StringEntity(rootObject.toString()); - postRequest.setEntity(entity); - HttpResponse postResponse = client.execute(postRequest); - assertEquals(postResponse.getStatusLine().getStatusCode(), 201, - "User has not been created in patch process successfully."); - Object responseObj = JSONValue.parse(EntityUtils.toString(postResponse.getEntity())); - EntityUtils.consume(postResponse.getEntity()); - String userId = ((JSONObject) responseObj).get(ID_ATTRIBUTE).toString(); - assertNotNull(userId); - String userResourcePath = getPath() + "/" + userId; - - claimMetadataManagementServiceClient = new ClaimMetadataManagementServiceClient(backendURL, sessionCookie); - claimMetadataManagementServiceClient.removeExternalClaim("urn:ietf:params:scim:schemas:core:2.0:User", - "urn:ietf:params:scim:schemas:core:2.0:User:name.honorificSuffix"); - HttpPatch request = new HttpPatch(userResourcePath); - StringEntity params = new StringEntity("{\"schemas\":[\"urn:ietf:params:scim:api:messages:2.0:PatchOp\"]," - + "\"Operations\":[{\"op\":\"replace\",\"path\":\"name\",\"value\":{\"givenName\":\"mahela\"," - + "\"familyName\":\"jayaxxxx\"}}]}"); - - request.setEntity(params); - request.addHeader(HttpHeaders.AUTHORIZATION, getAuthzHeader()); - request.addHeader(HttpHeaders.CONTENT_TYPE, "application/json"); - HttpResponse response = client.execute(request); - assertEquals(response.getStatusLine().getStatusCode(), 200, "User has not been updated successfully."); - Object responseObjAfterPatch = JSONValue.parse(EntityUtils.toString(response.getEntity())); - EntityUtils.consume(response.getEntity()); - String updatedGivenName = ((JSONObject) responseObjAfterPatch).get(NAME_ATTRIBUTE).toString(); - assertTrue(updatedGivenName.contains("mahela")); - } - private String getPath() { if (tenant.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { return SERVER_URL + SCIM2_USERS_ENDPOINT; diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/scim2/rest/api/customSchema/SCIM2CustomSchemaMeTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/scim2/rest/api/customSchema/SCIM2CustomSchemaMeTestCase.java index 4e8c4c67cf5..89ca5e534d2 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/scim2/rest/api/customSchema/SCIM2CustomSchemaMeTestCase.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/scim2/rest/api/customSchema/SCIM2CustomSchemaMeTestCase.java @@ -87,7 +87,7 @@ public class SCIM2CustomSchemaMeTestCase extends SCIM2BaseTest { private static final String MANAGER_EMAIL_CLAIM_ATTRIBUTE_URI = MANAGER_CLAIM_ATTRIBUTE_URI + "." + MANAGER_EMAIL_CLAIM_ATTRIBUTE_NAME; private static final String MANAGER_LOCAL_CLAIM_URI = "http://wso2.org/claims/manager"; - private static final String MANAGER_EMAIL_LOCAL_CLAIM_URI = "http://wso2.org/claims/emailaddress"; + private static final String MANAGER_EMAIL_LOCAL_CLAIM_URI = "http://wso2.org/claims/emails.work"; private static final String MANAGER_EMAIL_LOCAL_CLAIM_VALUE = "piraveena@gmail.com"; private static final String MANAGER_EMAIL_LOCAL_CLAIM_VALUE_AFTER_REPLACE = "piraveenaReplace@gmail.com"; diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/scim2/rest/api/customSchema/SCIM2CustomSchemaUserTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/scim2/rest/api/customSchema/SCIM2CustomSchemaUserTestCase.java index 57ba44cd3ba..3c5ca2cac1c 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/scim2/rest/api/customSchema/SCIM2CustomSchemaUserTestCase.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/scim2/rest/api/customSchema/SCIM2CustomSchemaUserTestCase.java @@ -88,7 +88,7 @@ public class SCIM2CustomSchemaUserTestCase extends SCIM2BaseTest { private static final String MANAGER_EMAIL_CLAIM_ATTRIBUTE_URI = MANAGER_CLAIM_ATTRIBUTE_URI + "." + MANAGER_EMAIL_CLAIM_ATTRIBUTE_NAME; private static final String MANAGER_LOCAL_CLAIM_URI = "http://wso2.org/claims/manager"; - private static final String MANAGER_EMAIL_LOCAL_CLAIM_URI = "http://wso2.org/claims/emailaddress"; + private static final String MANAGER_EMAIL_LOCAL_CLAIM_URI = "http://wso2.org/claims/emails.work"; private static final String MANAGER_EMAIL_LOCAL_CLAIM_VALUE = "piraveena@gmail.com"; private static final String MANAGER_EMAIL_LOCAL_CLAIM_VALUE_AFTER_REPLACE = "piraveenaReplace@gmail.com"; private static final String MANAGER_EMAIL_LOCAL_CLAIM_VALUE_AFTER_ADD = "piraveenaAdd@gmail.com"; diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/user/mgt/ReadWriteLDAPUserStoreManagerTestCase.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/user/mgt/ReadWriteLDAPUserStoreManagerTestCase.java index 8f98366ab90..bcadedb470a 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/user/mgt/ReadWriteLDAPUserStoreManagerTestCase.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/user/mgt/ReadWriteLDAPUserStoreManagerTestCase.java @@ -21,12 +21,20 @@ import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; -import org.wso2.carbon.integration.common.utils.mgt.ServerConfigurationManager; -import java.io.File; +import java.util.Arrays; +import java.util.Set; +import java.util.HashSet; public class ReadWriteLDAPUserStoreManagerTestCase extends UserManagementServiceAbstractTest { + // These attributes are not supported by the default LDAP schema. + private static final Set UNSUPPORTED_CLAIMS = new HashSet<>(Arrays.asList( + "http://wso2.org/claims/emailAddresses", + "http://wso2.org/claims/verifiedEmailAddresses", + "http://wso2.org/claims/mobileNumbers", + "http://wso2.org/claims/verifiedMobileNumbers")); + @BeforeClass(alwaysRun = true) public void configureServer() throws Exception { super.doInit(); @@ -52,5 +60,11 @@ protected void setUserPassword() { protected void setUserRole() { newUserRole = "ReadWriteLDAPUserRole"; } + + @Override + protected Set getExcludedClaims() { + + return UNSUPPORTED_CLAIMS; + } } diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/user/mgt/UserManagementServiceAbstractTest.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/user/mgt/UserManagementServiceAbstractTest.java index fb95862912f..59275740bb3 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/user/mgt/UserManagementServiceAbstractTest.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/user/mgt/UserManagementServiceAbstractTest.java @@ -36,7 +36,11 @@ import org.wso2.identity.integration.common.clients.UserProfileMgtServiceClient; import org.wso2.identity.integration.common.utils.ISIntegrationTest; +import java.util.Arrays; import java.io.File; +import java.util.Collections; +import java.util.Set; + import javax.activation.DataHandler; import javax.activation.FileDataSource; @@ -80,6 +84,16 @@ public void clean() throws Exception { } } + /** + * Retrieves a set of skipped claim URIs. + * + * @return Set of skipped claim URIs. + */ + protected Set getExcludedClaims() { + + return Collections.emptySet(); + } + @SetEnvironment(executionEnvironments = {ExecutionEnvironment.STANDALONE}) @Test(groups = "wso2.is", description = "Get all the role names") public void testGetAllRoleNames() throws Exception { @@ -304,27 +318,25 @@ public void testListUserByClaim() throws Exception { = new UserProfileMgtServiceClient(backendURL, getSessionCookie()); UserProfileDTO profile = userProfileMgtServiceClient.getUserProfile(newUserName, "default"); - UserFieldDTO[] fields = userProfileMgtServiceClient.getProfileFieldsForInternalStore().getFieldValues(); String profileConfigs = profile.getProfileName(); - for (UserFieldDTO field : fields) { - if (field.getDisplayName().equalsIgnoreCase("Last Name")) { - field.setFieldValue(newUserName + "LastName"); - continue; - } - - if (field.getRequired()) { - if (field.getDisplayName().equalsIgnoreCase("Email")) { - field.setFieldValue(newUserName + "@wso2.com"); - } else { - field.setFieldValue(newUserName); + Set excludedClaims = getExcludedClaims(); + + UserFieldDTO[] fields = Arrays.stream( + userProfileMgtServiceClient.getProfileFieldsForInternalStore().getFieldValues()) + .filter(field -> !excludedClaims.contains(field.getClaimUri())) + .map(field -> { + if ("Last Name".equalsIgnoreCase(field.getDisplayName())) { + field.setFieldValue(newUserName + "LastName"); + } else if (field.getRequired()) { + field.setFieldValue("Email".equalsIgnoreCase(field.getDisplayName()) + ? newUserName + "@wso2.com" + : newUserName); + } else if (field.getFieldValue() == null) { + field.setFieldValue(""); } - continue; - } - if (field.getFieldValue() == null) { - field.setFieldValue(""); - } + return field; + }).toArray(UserFieldDTO[]::new); - } //creating a new profile with updated values UserProfileDTO newProfile = new UserProfileDTO(); newProfile.setProfileName(profile.getProfileName()); diff --git a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/util/Utils.java b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/util/Utils.java index 0d31062c812..7d3af0bf5f7 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/util/Utils.java +++ b/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/util/Utils.java @@ -37,6 +37,9 @@ import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; import org.wso2.carbon.automation.engine.context.beans.Tenant; import org.wso2.carbon.automation.engine.context.beans.User; import org.wso2.carbon.automation.engine.frameworkutils.FrameworkPathUtil; @@ -62,6 +65,9 @@ import java.util.List; import java.util.Map; import java.util.StringJoiner; +import java.util.Iterator; +import java.util.Set; +import java.util.HashSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -700,6 +706,36 @@ public static String getBasicAuthHeader(User userInfo) { return encodedBasicAuthInfo.getAuthorizationHeader(); } + public static boolean areJSONObjectsEqual(Object ob1, Object ob2) throws JSONException { + + Object obj1Converted = convertJsonElement(ob1); + Object obj2Converted = convertJsonElement(ob2); + return obj1Converted.equals(obj2Converted); + } + + private static Object convertJsonElement(Object elem) throws JSONException { + + if (elem instanceof JSONObject) { + JSONObject obj = (JSONObject) elem; + Iterator keys = obj.keys(); + Map jsonMap = new HashMap<>(); + while (keys.hasNext()) { + String key = keys.next(); + jsonMap.put(key, convertJsonElement(obj.get(key))); + } + return jsonMap; + } else if (elem instanceof JSONArray) { + JSONArray arr = (JSONArray) elem; + Set jsonSet = new HashSet<>(); + for (int i = 0; i < arr.length(); i++) { + jsonSet.add(convertJsonElement(arr.get(i))); + } + return jsonSet; + } else { + return elem; + } + } + /** * Get Java Major Version from System Property. * diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/actions/response/error-response.json b/modules/integration/tests-integration/tests-backend/src/test/resources/actions/response/error-response.json new file mode 100644 index 00000000000..bb71eeca3c7 --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/resources/actions/response/error-response.json @@ -0,0 +1,5 @@ +{ + "actionStatus": "ERROR", + "errorMessage": "Some error message", + "errorDescription": "Some error description" +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/actions/response/failure-response.json b/modules/integration/tests-integration/tests-backend/src/test/resources/actions/response/failure-response.json new file mode 100644 index 00000000000..cffa0126dbb --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/resources/actions/response/failure-response.json @@ -0,0 +1,5 @@ +{ + "actionStatus": "FAILED", + "failureReason": "Some failure reason", + "failureDescription": "Some description" +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/actions/response/pre-issue-access-token-response-code-before-refresh.json b/modules/integration/tests-integration/tests-backend/src/test/resources/actions/response/pre-issue-access-token-response-code-before-refresh.json new file mode 100644 index 00000000000..4736e90ac23 --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/resources/actions/response/pre-issue-access-token-response-code-before-refresh.json @@ -0,0 +1,13 @@ +{ + "actionStatus": "SUCCESS", + "operations": [ + { + "op": "add", + "path": "/accessToken/claims/-", + "value": { + "name": "custom_claim_string_0", + "value": "testCustomClaim0" + } + } + ] +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/IIA001Policy.xml b/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/IIA001Policy.xml deleted file mode 100644 index f40f0c208af..00000000000 --- a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/IIA001Policy.xml +++ /dev/null @@ -1,68 +0,0 @@ - - - - Policy for Conformance Test IIA001. - - - - - Julius Hibbert can read or write Bart Simpson's medical record. - - - - - - Julius Hibbert - - - - - - - - http://medico.com/record/patient/BartSimpson - - - - - - - - read - - - - - - write - - - - - - - diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/IIA001Request.xml b/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/IIA001Request.xml deleted file mode 100644 index 5414b78b65b..00000000000 --- a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/IIA001Request.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - Julius Hibbert - - - - - http://medico.com/record/patient/BartSimpson - - - - - read - - - - diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/IIA003Policy.xml b/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/IIA003Policy.xml deleted file mode 100644 index f4829fa597a..00000000000 --- a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/IIA003Policy.xml +++ /dev/null @@ -1,70 +0,0 @@ - - - - Policy for Conformance Test IIA003. - - - - - A subject with a "bogus" attribute with a value of - "Physician" can read or write Bart Simpson's medical - record. - - - - - - Physician - - - - - - - - http://medico.com/record/patient/BartSimpson - - - - - - - - read - - - - - - write - - - - - - - diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/IIA003Request.xml b/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/IIA003Request.xml deleted file mode 100644 index 2dc5861db12..00000000000 --- a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/IIA003Request.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - Julius Hibbert - - - - - http://medico.com/record/patient/BartSimpson - - - - - read - - diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/default-identity.xml b/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/default-identity.xml index ead58e5c6ca..033d1fc9803 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/default-identity.xml +++ b/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/default-identity.xml @@ -296,7 +296,6 @@ - - @@ -503,9 +502,6 @@ /permission/admin/manage/identity/applicationmgt/view - - /permission/admin/manage/identity/pep - /permission/admin/manage/identity/usermgt diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/identityMgt/identity-identitymgtlistener-enabled.xml b/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/identityMgt/identity-identitymgtlistener-enabled.xml index e3bb536820d..4a18c4b8350 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/identityMgt/identity-identitymgtlistener-enabled.xml +++ b/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/identityMgt/identity-identitymgtlistener-enabled.xml @@ -302,7 +302,6 @@ - diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/identityMgt/identity-ssoservice-entityid-changed.xml b/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/identityMgt/identity-ssoservice-entityid-changed.xml index a231d36d05c..ebce83e2a81 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/identityMgt/identity-ssoservice-entityid-changed.xml +++ b/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/identityMgt/identity-ssoservice-entityid-changed.xml @@ -195,7 +195,6 @@ - diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/xacml_scope_validator.toml b/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/jit/jit_user_association_config.toml similarity index 79% rename from modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/xacml_scope_validator.toml rename to modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/jit/jit_user_association_config.toml index 12abe763689..47f88e17cb5 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/xacml_scope_validator.toml +++ b/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/jit/jit_user_association_config.toml @@ -26,7 +26,12 @@ password = "$env{SHARED_DATABASE_PASSWORD}" [keystore.primary] file_name = "wso2carbon.p12" password = "wso2carbon" +type = "PKCS12" -[oauth] -drop_unregistered_scopes= false -allowed_scopes= [] +[truststore] +file_name = "client-truststore.p12" +password = "wso2carbon" +type = "PKCS12" + +[authentication.jit_provisioning] +associating_to_existing_user = "true" diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/notification-mgt/config/entitlementNotificationMgt.properties b/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/notification-mgt/config/entitlementNotificationMgt.properties deleted file mode 100644 index 971d06129c1..00000000000 --- a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/notification-mgt/config/entitlementNotificationMgt.properties +++ /dev/null @@ -1,20 +0,0 @@ -#Wed Dec 16 17:42:44 IST 2015 -json.subscription.policyUpdate.endpoint.pepEndpoint1.username=admin -email.subscription.userOperation.endpoint.privateMail.subject=User operation change information to private mail -json.subscription.policyUpdate.jsonContentTemplate=/Users/johann/product-is/modules/integration/tests-integration/tests-backend/src/test/resources//artifacts/IS/notification-mgt/templates/entitlement -json.subscription.1=policyUpdate -json.subscription.policyUpdate.endpoint.pepEndpoint1.AuthenticationRequired=true -email.subscription.1=userOperation -email.subscription.userOperation.salutation=Admin -email.subscription.userOperation.endpoint.1=privateMail -email.subscription.userOperation.endpoint.privateMail.address=privatemail@gmail.com -email.subscription.userOperation.endpoint.privateMail.salutation=Admin private mail -module.name.2=email -json.subscription.policyUpdate.endpoint.1=pepEndpoint1 -module.name.1=json -email.subscription.userOperation.template=templatePath/template1 -json.subscription.policyUpdate.jsonId=3232 -threadPool.size=10 -email.subscription.userOperation.subject=User operation change information -json.subscription.policyUpdate.endpoint.pepEndpoint1.password=admin -json.subscription.policyUpdate.endpoint.pepEndpoint1.address=https\://localhost\:9853/wso2/scim/Users diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/notification-mgt/templates/entitlement b/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/notification-mgt/templates/entitlement deleted file mode 100644 index 93435cba425..00000000000 --- a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/notification-mgt/templates/entitlement +++ /dev/null @@ -1 +0,0 @@ -{"schemas":[],"name":{"familyName":"(action)","givenName":"(action)"},"userName":"(action)","password":"hasinitg","emails":[{"primary":true,"value":"hasini_home.com","type":"home"},{"value":"hasini_work.com","type":"work"}]} \ No newline at end of file diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/oauth/IDENTITY6777-identity.xml b/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/oauth/IDENTITY6777-identity.xml index feaa3103420..69e2ce6ad2a 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/oauth/IDENTITY6777-identity.xml +++ b/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/oauth/IDENTITY6777-identity.xml @@ -263,7 +263,6 @@ - diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/oauth/encrypt-decrypt-persistence-enabled-identity.xml b/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/oauth/encrypt-decrypt-persistence-enabled-identity.xml index 808ed6fee21..9f660dcd74b 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/oauth/encrypt-decrypt-persistence-enabled-identity.xml +++ b/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/oauth/encrypt-decrypt-persistence-enabled-identity.xml @@ -289,7 +289,6 @@ - @@ -517,9 +516,6 @@ /permission/admin/manage/identity/applicationmgt/view - - /permission/admin/manage/identity/pep - /permission/admin/manage/identity/usermgt @@ -568,7 +564,6 @@ /api/identity/recovery/v0.9/ /oauth2/ /scim2/ - /api/identity/entitlement/ /api/identity/oauth2/dcr/v1.1/ diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/openId/dumbconsumerwithclaims/travelocity.properties b/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/openId/dumbconsumerwithclaims/travelocity.properties deleted file mode 100644 index cc735665edd..00000000000 --- a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/openId/dumbconsumerwithclaims/travelocity.properties +++ /dev/null @@ -1,89 +0,0 @@ -EnableSAML2SSOLogin=true -EnableOpenIDLogin=true -EnableOAuth2SAML2Grant=false - -#Url to do send SAML2 SSO AuthnRequest -SAML2SSOURL=samlsso - -#Url to do initiate OAuth2 SAML2 Grant Request -OAuth2SAML2GrantURL=token - -#Url to initiate OpenID Authentication Request -OpenIdURL=openid - -#URIs to skip SSOAgentFilter; comma separated values -SkipURIs=/travelocity.com-openid-dumbconsumerwithclaims/index.jsp - -#A unique identifier for this SAML 2.0 Service Provider application -SAML2.SPEntityId=travelocity.com-openid-dumbconsumerwithclaims - -#The URL of the SAML 2.0 Assertion Consumer -SAML2.ACSURL=http://localhost:8490/travelocity.com-openid-dumbconsumerwithclaims/home.jsp - -#A unique identifier for this SAML 2.0 Service Provider application -SAML2.IdPEntityId=localhost - -#The URL of the SAML 2.0 Identity Provider -SAML2.IdPURL=https://localhost:9853/samlsso - -#Identifier given for the Service Provider for SAML 2.0 attributes -#exchange -#SAML2.AttributeConsumingServiceIndex=1701087467 - -#Specify if SingleLogout is enabled/disabled -SAML2.EnableSLO=true - -#This is the URL that is used for SLO -SAML2.SLOURL=logout - -#Specify if SAMLResponse element is signed -SAML2.EnableResponseSigning=true - -#Specify if SAMLAssertion element is signed -SAML2.EnableAssertionSigning=true - -#Specify if SAMLAssertion element is encrypted -SAML2.EnableAssertionEncryption=false - -#Specify if AuthnRequests and LogoutRequests should be signed -SAML2.EnableRequestSigning=true - -#Password of the KeyStore for SAML and OpenID -KeyStorePassword=wso2carbon - -#Alias of the IdP's public certificate -IdPPublicCertAlias=wso2carbon - -#Alias of the SP's private key -PrivateKeyAlias=wso2carbon - -#Private key password to retrieve the private key used to sign -#AuthnRequest and LogoutRequest messages -PrivateKeyPassword=wso2carbon - -#OAuth2 token endpoint URL -SAML2.OAuth2TokenURL=https://localhost:9853/oauth2/token - -#OAuth2 Client ID -SAML2.OAuth2ClientId=Qn5DQHCYfshxeZh6R9SL1HM2lsMa - -#OAuth2 Client Secret -SAML2.OAuth2ClientSecret=cbkAs1gajdwPAMbrSR54hPAIcz0a - -#OpenId Provider Url -OpenId.ProviderURL=https://localhost:9853/openid/ - -#openid.return_to parameter -OpenId.ReturnToURL=http://localhost:8490/travelocity.com-openid-dumbconsumerwithclaims/home.jsp - -#Custom SAML post binding request page -#SAML.PostBinding.RequestPage=path/to/the/html - -#Additional request parameters -#SAML.Request.Query.Param=&forceAuth=true - -#Specify whether the consumer requests user attributes from the provider -OpenId.EnableAttributeExchange=true - -#Specify whether the consumer runs in dumb mode -OpenId.EnableDumbMode=true diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/openId/dumbconsumerwithoutclaims/travelocity.properties b/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/openId/dumbconsumerwithoutclaims/travelocity.properties deleted file mode 100644 index 59adfa26110..00000000000 --- a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/openId/dumbconsumerwithoutclaims/travelocity.properties +++ /dev/null @@ -1,89 +0,0 @@ -EnableSAML2SSOLogin=true -EnableOpenIDLogin=true -EnableOAuth2SAML2Grant=false - -#Url to do send SAML2 SSO AuthnRequest -SAML2SSOURL=samlsso - -#Url to do initiate OAuth2 SAML2 Grant Request -OAuth2SAML2GrantURL=token - -#Url to initiate OpenID Authentication Request -OpenIdURL=openid - -#URIs to skip SSOAgentFilter; comma separated values -SkipURIs=/travelocity.com-openid-dumbconsumerwithoutclaims/index.jsp - -#A unique identifier for this SAML 2.0 Service Provider application -SAML2.SPEntityId=travelocity.com-openid-dumbconsumerwithoutclaims - -#The URL of the SAML 2.0 Assertion Consumer -SAML2.ACSURL=http://localhost:8490/travelocity.com-openid-dumbconsumerwithoutclaims/home.jsp - -#A unique identifier for this SAML 2.0 Service Provider application -SAML2.IdPEntityId=localhost - -#The URL of the SAML 2.0 Identity Provider -SAML2.IdPURL=https://localhost:9853/samlsso - -#Identifier given for the Service Provider for SAML 2.0 attributes -#exchange -#SAML2.AttributeConsumingServiceIndex=1701087467 - -#Specify if SingleLogout is enabled/disabled -SAML2.EnableSLO=true - -#This is the URL that is used for SLO -SAML2.SLOURL=logout - -#Specify if SAMLResponse element is signed -SAML2.EnableResponseSigning=true - -#Specify if SAMLAssertion element is signed -SAML2.EnableAssertionSigning=true - -#Specify if SAMLAssertion element is encrypted -SAML2.EnableAssertionEncryption=false - -#Specify if AuthnRequests and LogoutRequests should be signed -SAML2.EnableRequestSigning=true - -#Password of the KeyStore for SAML and OpenID -KeyStorePassword=wso2carbon - -#Alias of the IdP's public certificate -IdPPublicCertAlias=wso2carbon - -#Alias of the SP's private key -PrivateKeyAlias=wso2carbon - -#Private key password to retrieve the private key used to sign -#AuthnRequest and LogoutRequest messages -PrivateKeyPassword=wso2carbon - -#OAuth2 token endpoint URL -SAML2.OAuth2TokenURL=https://localhost:9853/oauth2/token - -#OAuth2 Client ID -SAML2.OAuth2ClientId=Qn5DQHCYfshxeZh6R9SL1HM2lsMa - -#OAuth2 Client Secret -SAML2.OAuth2ClientSecret=cbkAs1gajdwPAMbrSR54hPAIcz0a - -#OpenId Provider Url -OpenId.ProviderURL=https://localhost:9853/openid/ - -#openid.return_to parameter -OpenId.ReturnToURL=http://localhost:8490/travelocity.com-openid-dumbconsumerwithoutclaims/home.jsp - -#Custom SAML post binding request page -#SAML.PostBinding.RequestPage=path/to/the/html - -#Additional request parameters -#SAML.Request.Query.Param=&forceAuth=true - -#Specify whether the consumer requests user attributes from the provider -OpenId.EnableAttributeExchange=false - -#Specify whether the consumer runs in dumb mode -OpenId.EnableDumbMode=true diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/openId/identity-skipuserconsent.xml b/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/openId/identity-skipuserconsent.xml deleted file mode 100644 index 2f21a0fd86b..00000000000 --- a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/openId/identity-skipuserconsent.xml +++ /dev/null @@ -1,321 +0,0 @@ - - - - - - - - - jdbc/WSO2CarbonDB - - - - - - - - - ${carbon.home}/repository/resources/security/userRP.p12 - - - PKCS12 - - wso2carbon - - wso2carbon - - - - ${carbon.home}/conf/keystores - - - - SelfAndManaged - CertValidate - - - - - - - - - - https://localhost:9853/openidserver - https://localhost:9853/openid/ - - true - - 7200 - - false - - false - - 36000 - - false - org.wso2.carbon.identity.provider.openid.claims.DefaultClaimsRetriever - - - - https://localhost:9853/oauth/request-token - https://localhost:9853/oauth/access-token - https://localhost:9853/oauth/authorize-url - - 300 - - 3600 - - 3600 - - 84600 - - 300 - - true - - true - - org.wso2.carbon.identity.oauth.tokenprocessor.PlainTextPersistenceProcessor - - - org.wso2.carbon.identity.oauth2.token.handlers.clientauth.BasicAuthClientAuthHandler - - - - - token - org.wso2.carbon.identity.oauth2.authz.handlers.TokenResponseTypeHandler - - - code - org.wso2.carbon.identity.oauth2.authz.handlers.CodeResponseTypeHandler - - - - - - authorization_code - org.wso2.carbon.identity.oauth2.token.handlers.grant.AuthorizationCodeGrantHandler - - - password - org.wso2.carbon.identity.oauth2.token.handlers.grant.PasswordGrantHandler - - - refresh_token - org.wso2.carbon.identity.oauth2.token.handlers.grant.RefreshGrantHandler - - - client_credentials - org.wso2.carbon.identity.oauth2.token.handlers.grant.ClientCredentialsGrantHandler - - - urn:ietf:params:oauth:grant-type:saml2-bearer - org.wso2.carbon.identity.oauth2.token.handlers.grant.saml.SAML2BearerGrantHandler - - - iwa:ntlm - org.wso2.carbon.identity.oauth2.token.handlers.grant.iwa.ntlm.NTLMAuthenticationGrantHandler - - - - - - - - - false - - - - false - - - - - false - org.wso2.carbon.identity.oauth2.authcontext.JWTTokenGenerator - org.wso2.carbon.identity.oauth2.authcontext.DefaultClaimsRetriever - http://wso2.org/claims - SHA256withRSA - 15 - - - - - - org.wso2.carbon.identity.openidconnect.DefaultIDTokenBuilder - https://localhost:9853/oauth2endpoints/token - http://wso2.org/claims/givenname - org.wso2.carbon.identity.openidconnect.SAMLAssertionClaimsCallback - 3600 - http://wso2.org/claims - org.wso2.carbon.identity.oauth.endpoint.user.impl.UserInfoUserStoreClaimRetriever - org.wso2.carbon.identity.oauth.endpoint.user.impl.UserInforRequestDefaultValidator - org.wso2.carbon.identity.oauth.endpoint.user.impl.UserInfoISAccessTokenValidator - org.wso2.carbon.identity.oauth.endpoint.user.impl.UserInfoJSONResponseBuilder - false - - - - - true - 0 - 5 - - - - - - - - - - - - gtalk - talk.google.com - 5222 - gmail.com - multifactor1@gmail.com - wso2carbon - - - - - - localhost - https://localhost:9853/samlsso - 5 - 60000 - false - 36000 - - org.wso2.carbon.identity.sso.saml.attributes.UserAttributeStatementBuilder - http://wso2.org/claims - false - org.wso2.carbon.identity.sso.saml.builders.claims.DefaultClaimsRetriever - org.wso2.carbon.identity.sso.saml.builders.encryption.DefaultSSOEncrypter - org.wso2.carbon.identity.sso.saml.builders.signature.DefaultSSOSigner - org.wso2.carbon.identity.sso.saml.validators.SAML2HTTPRedirectDeflateSignatureValidator - - - - 5 - false - - - - - - - true - 36000 - - - true - - - true - - ${Ports.ThriftEntitlementReceivePort} - 10000 - - ${carbon.home}/repository/resources/security/wso2carbon.p12 - wso2carbon - - - - - - - - true - - - true - - true - - - - true - true - ! - 2 - - false - 3 - - - - 3 - true - - false - false - true - - - - - true - true - - true - - - - - true - true - - true - - false - - - - - - 5 - - - 10 - local://services - - - - diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/openId/openid-app-build.xml b/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/openId/openid-app-build.xml deleted file mode 100644 index d4adb66c448..00000000000 --- a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/openId/openid-app-build.xml +++ /dev/null @@ -1,114 +0,0 @@ - - - - - - This script builds four war files for the travelocity app for combinations of consumer type and openid attribute - exchange - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/openId/smartconsumerwithclaims/travelocity.properties b/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/openId/smartconsumerwithclaims/travelocity.properties deleted file mode 100644 index 5169535a44d..00000000000 --- a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/openId/smartconsumerwithclaims/travelocity.properties +++ /dev/null @@ -1,89 +0,0 @@ -EnableSAML2SSOLogin=true -EnableOpenIDLogin=true -EnableOAuth2SAML2Grant=false - -#Url to do send SAML2 SSO AuthnRequest -SAML2SSOURL=samlsso - -#Url to do initiate OAuth2 SAML2 Grant Request -OAuth2SAML2GrantURL=token - -#Url to initiate OpenID Authentication Request -OpenIdURL=openid - -#URIs to skip SSOAgentFilter; comma separated values -SkipURIs=/travelocity.com-openid-smartconsumerwithclaims/index.jsp - -#A unique identifier for this SAML 2.0 Service Provider application -SAML2.SPEntityId=travelocity.com-openid-smartconsumerwithclaims - -#The URL of the SAML 2.0 Assertion Consumer -SAML2.ACSURL=http://localhost:8490/travelocity.com-openid-smartconsumerwithclaims/home.jsp - -#A unique identifier for this SAML 2.0 Service Provider application -SAML2.IdPEntityId=localhost - -#The URL of the SAML 2.0 Identity Provider -SAML2.IdPURL=https://localhost:9853/samlsso - -#Identifier given for the Service Provider for SAML 2.0 attributes -#exchange -#SAML2.AttributeConsumingServiceIndex=1701087467 - -#Specify if SingleLogout is enabled/disabled -SAML2.EnableSLO=true - -#This is the URL that is used for SLO -SAML2.SLOURL=logout - -#Specify if SAMLResponse element is signed -SAML2.EnableResponseSigning=true - -#Specify if SAMLAssertion element is signed -SAML2.EnableAssertionSigning=true - -#Specify if SAMLAssertion element is encrypted -SAML2.EnableAssertionEncryption=false - -#Specify if AuthnRequests and LogoutRequests should be signed -SAML2.EnableRequestSigning=true - -#Password of the KeyStore for SAML and OpenID -KeyStorePassword=wso2carbon - -#Alias of the IdP's public certificate -IdPPublicCertAlias=wso2carbon - -#Alias of the SP's private key -PrivateKeyAlias=wso2carbon - -#Private key password to retrieve the private key used to sign -#AuthnRequest and LogoutRequest messages -PrivateKeyPassword=wso2carbon - -#OAuth2 token endpoint URL -SAML2.OAuth2TokenURL=https://localhost:9853/oauth2/token - -#OAuth2 Client ID -SAML2.OAuth2ClientId=Qn5DQHCYfshxeZh6R9SL1HM2lsMa - -#OAuth2 Client Secret -SAML2.OAuth2ClientSecret=cbkAs1gajdwPAMbrSR54hPAIcz0a - -#OpenId Provider Url -OpenId.ProviderURL=https://localhost:9853/openid/ - -#openid.return_to parameter -OpenId.ReturnToURL=http://localhost:8490/travelocity.com-openid-smartconsumerwithclaims/home.jsp - -#Custom SAML post binding request page -#SAML.PostBinding.RequestPage=path/to/the/html - -#Additional request parameters -#SAML.Request.Query.Param=&forceAuth=true - -#Specify whether the consumer requests user attributes from the provider -OpenId.EnableAttributeExchange=true - -#Specify whether the consumer runs in dumb mode -OpenId.EnableDumbMode=false diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/openId/smartconsumerwithoutclaims/travelocity.properties b/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/openId/smartconsumerwithoutclaims/travelocity.properties deleted file mode 100644 index c379912c713..00000000000 --- a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/openId/smartconsumerwithoutclaims/travelocity.properties +++ /dev/null @@ -1,89 +0,0 @@ -EnableSAML2SSOLogin=true -EnableOpenIDLogin=true -EnableOAuth2SAML2Grant=false - -#Url to do send SAML2 SSO AuthnRequest -SAML2SSOURL=samlsso - -#Url to do initiate OAuth2 SAML2 Grant Request -OAuth2SAML2GrantURL=token - -#Url to initiate OpenID Authentication Request -OpenIdURL=openid - -#URIs to skip SSOAgentFilter; comma separated values -SkipURIs=/travelocity.com-openid-smartconsumerwithoutclaims/index.jsp - -#A unique identifier for this SAML 2.0 Service Provider application -SAML2.SPEntityId=travelocity.com-openid-smartconsumerwithoutclaims - -#The URL of the SAML 2.0 Assertion Consumer -SAML2.ACSURL=http://localhost:8490/travelocity.com-openid-smartconsumerwithoutclaims/home.jsp - -#A unique identifier for this SAML 2.0 Service Provider application -SAML2.IdPEntityId=localhost - -#The URL of the SAML 2.0 Identity Provider -SAML2.IdPURL=https://localhost:9853/samlsso - -#Identifier given for the Service Provider for SAML 2.0 attributes -#exchange -#SAML2.AttributeConsumingServiceIndex=1701087467 - -#Specify if SingleLogout is enabled/disabled -SAML2.EnableSLO=true - -#This is the URL that is used for SLO -SAML2.SLOURL=logout - -#Specify if SAMLResponse element is signed -SAML2.EnableResponseSigning=true - -#Specify if SAMLAssertion element is signed -SAML2.EnableAssertionSigning=true - -#Specify if SAMLAssertion element is encrypted -SAML2.EnableAssertionEncryption=false - -#Specify if AuthnRequests and LogoutRequests should be signed -SAML2.EnableRequestSigning=true - -#Password of the KeyStore for SAML and OpenID -KeyStorePassword=wso2carbon - -#Alias of the IdP's public certificate -IdPPublicCertAlias=wso2carbon - -#Alias of the SP's private key -PrivateKeyAlias=wso2carbon - -#Private key password to retrieve the private key used to sign -#AuthnRequest and LogoutRequest messages -PrivateKeyPassword=wso2carbon - -#OAuth2 token endpoint URL -SAML2.OAuth2TokenURL=https://localhost:9853/oauth2/token - -#OAuth2 Client ID -SAML2.OAuth2ClientId=Qn5DQHCYfshxeZh6R9SL1HM2lsMa - -#OAuth2 Client Secret -SAML2.OAuth2ClientSecret=cbkAs1gajdwPAMbrSR54hPAIcz0a - -#OpenId Provider Url -OpenId.ProviderURL=https://localhost:9853/openid/ - -#openid.return_to parameter -OpenId.ReturnToURL=http://localhost:8490/travelocity.com-openid-smartconsumerwithoutclaims/home.jsp - -#Custom SAML post binding request page -#SAML.PostBinding.RequestPage=path/to/the/html - -#Additional request parameters -#SAML.Request.Query.Param=&forceAuth=true - -#Specify whether the consumer requests user attributes from the provider -OpenId.EnableAttributeExchange=false - -#Specify whether the consumer runs in dumb mode -OpenId.EnableDumbMode=false diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/saml/identity-mgt-listener-enabled.xml b/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/saml/identity-mgt-listener-enabled.xml index b30b9dec2e7..ea17b5195f9 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/saml/identity-mgt-listener-enabled.xml +++ b/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/saml/identity-mgt-listener-enabled.xml @@ -302,7 +302,6 @@ - diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/saml/registry.xml b/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/saml/registry.xml index f618b50895e..c25a2adfeb0 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/saml/registry.xml +++ b/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/saml/registry.xml @@ -33,11 +33,6 @@ jdbc/WSO2CarbonDB - - - application/xacml-policy+xml - - - @@ -501,9 +500,6 @@ /permission/admin/manage/identity/applicationmgt/view - - /permission/admin/manage/identity/pep - /permission/admin/manage/identity/usermgt @@ -552,7 +548,6 @@ /api/identity/recovery/v0.9/ /oauth2/ /scim2/ - /api/identity/entitlement/ /api/identity/oauth2/dcr/v1.1/ diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/user/enable_email_username_deployment.toml b/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/user/enable_email_username_deployment.toml index 413a298408f..42289666b32 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/user/enable_email_username_deployment.toml +++ b/modules/integration/tests-integration/tests-backend/src/test/resources/artifacts/IS/user/enable_email_username_deployment.toml @@ -47,3 +47,6 @@ enable_email_domain = true [identity_mgt.events.schemes.liteUserRegistration.properties] enable = true + +[notification_templates] +enable_unicode_support = true diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/backupIdentity.xml b/modules/integration/tests-integration/tests-backend/src/test/resources/backupIdentity.xml index 5164247b571..bd2d322a7d0 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/resources/backupIdentity.xml +++ b/modules/integration/tests-integration/tests-backend/src/test/resources/backupIdentity.xml @@ -187,7 +187,6 @@ - diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/entitlement/json/complexMDPRequest.json b/modules/integration/tests-integration/tests-backend/src/test/resources/entitlement/json/complexMDPRequest.json deleted file mode 100644 index 8fa5397be6a..00000000000 --- a/modules/integration/tests-integration/tests-backend/src/test/resources/entitlement/json/complexMDPRequest.json +++ /dev/null @@ -1,68 +0,0 @@ -{ - "Request": { - "http://wso2.org/identity/user": [ - { - "Attribute": [ - { - "AttributeId": "http://wso2.org/identity/user/username", - "Value": "adminUser", - "IncludeInResult": true, - "DataType": "string" - } - ] - },{ - "Attribute": [ - { - "AttributeId": "http://wso2.org/identity/user/username", - "Value": "publicUser", - "IncludeInResult": true, - "DataType": "string" - } - ] - } ], - - "Resource": { - "Attribute": [ - { - "AttributeId": "urn:oasis:names:tc:xacml:1.0:resource:resource-id", - "Value": "index.jsp", - "IncludeInResult": true, - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - }, - "Action": [{ - "Attribute": [{ - "AttributeId": "urn:oasis:names:tc:xacml:1.0:action:action-id", - "Value": "view-welcome", - "IncludeInResult": true, - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - },{ - "Attribute": [{ - "AttributeId": "urn:oasis:names:tc:xacml:1.0:action:action-id", - "Value": "view-status", - "IncludeInResult": true, - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - },{ - "Attribute": [{ - "AttributeId": "urn:oasis:names:tc:xacml:1.0:action:action-id", - "Value": "view-summary", - "IncludeInResult": true, - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - },{ - "Attribute": [{ - "AttributeId": "urn:oasis:names:tc:xacml:1.0:action:action-id", - "Value": "modify-welcome", - "IncludeInResult": true, - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - } ] - } -} diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/entitlement/json/complexMDPResponse.json b/modules/integration/tests-integration/tests-backend/src/test/resources/entitlement/json/complexMDPResponse.json deleted file mode 100644 index 13aa99d0afd..00000000000 --- a/modules/integration/tests-integration/tests-backend/src/test/resources/entitlement/json/complexMDPResponse.json +++ /dev/null @@ -1,368 +0,0 @@ -{ - "Response": [ - { - "Decision": "Permit", - "Status": { - "StatusCode": { - "Value": "urn:oasis:names:tc:xacml:1.0:status:ok" - } - }, - "Action": { - "Attribute": [ - { - "AttributeId": "urn:oasis:names:tc:xacml:1.0:action:action-id", - "Value": "view-summary", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - }, - "http://wso2.org/identity/user": { - "Attribute": [ - { - "AttributeId": "http://wso2.org/identity/user/username", - "Value": "publicUser", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - }, - "Resource": { - "Attribute": [ - { - "AttributeId": "urn:oasis:names:tc:xacml:1.0:resource:resource-id", - "Value": "index.jsp", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - } - }, - { - "Decision": "Permit", - "Status": { - "StatusCode": { - "Value": "urn:oasis:names:tc:xacml:1.0:status:ok" - } - }, - "Action": { - "Attribute": [ - { - "AttributeId": "urn:oasis:names:tc:xacml:1.0:action:action-id", - "Value": "modify-welcome", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - }, - "Resource": { - "Attribute": [ - { - "AttributeId": "urn:oasis:names:tc:xacml:1.0:resource:resource-id", - "Value": "index.jsp", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - }, - "http://wso2.org/identity/user": { - "Attribute": [ - { - "AttributeId": "http://wso2.org/identity/user/username", - "Value": "adminUser", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - } - }, - { - "Decision": "Deny", - "Status": { - "StatusCode": { - "Value": "urn:oasis:names:tc:xacml:1.0:status:ok" - } - }, - "Obligations": [ - { - "Id": "fail_to_permit", - "AttributeAssignments": [ - { - "AttributeId": "obligation-id", - "Value": "You can access the resource index.jsp", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - } - ], - "Resource": { - "Attribute": [ - { - "AttributeId": "urn:oasis:names:tc:xacml:1.0:resource:resource-id", - "Value": "index.jsp", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - }, - "Action": { - "Attribute": [ - { - "AttributeId": "urn:oasis:names:tc:xacml:1.0:action:action-id", - "Value": "view-status", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - }, - "http://wso2.org/identity/user": { - "Attribute": [ - { - "AttributeId": "http://wso2.org/identity/user/username", - "Value": "adminUser", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - } - }, - { - "Decision": "Permit", - "Status": { - "StatusCode": { - "Value": "urn:oasis:names:tc:xacml:1.0:status:ok" - } - }, - "Action": { - "Attribute": [ - { - "AttributeId": "urn:oasis:names:tc:xacml:1.0:action:action-id", - "Value": "view-welcome", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - }, - "Resource": { - "Attribute": [ - { - "AttributeId": "urn:oasis:names:tc:xacml:1.0:resource:resource-id", - "Value": "index.jsp", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - }, - "http://wso2.org/identity/user": { - "Attribute": [ - { - "AttributeId": "http://wso2.org/identity/user/username", - "Value": "publicUser", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - } - }, - { - "Decision": "Deny", - "Status": { - "StatusCode": { - "Value": "urn:oasis:names:tc:xacml:1.0:status:ok" - } - }, - "Obligations": [ - { - "Id": "fail_to_permit", - "AttributeAssignments": [ - { - "AttributeId": "obligation-id", - "Value": "You can access the resource index.jsp", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - } - ], - "Action": { - "Attribute": [ - { - "AttributeId": "urn:oasis:names:tc:xacml:1.0:action:action-id", - "Value": "view-summary", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - }, - "Resource": { - "Attribute": [ - { - "AttributeId": "urn:oasis:names:tc:xacml:1.0:resource:resource-id", - "Value": "index.jsp", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - }, - "http://wso2.org/identity/user": { - "Attribute": [ - { - "AttributeId": "http://wso2.org/identity/user/username", - "Value": "adminUser", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - } - }, - { - "Decision": "Deny", - "Status": { - "StatusCode": { - "Value": "urn:oasis:names:tc:xacml:1.0:status:ok" - } - }, - "Obligations": [ - { - "Id": "fail_to_permit", - "AttributeAssignments": [ - { - "AttributeId": "obligation-id", - "Value": "You can access the resource index.jsp", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - } - ], - "http://wso2.org/identity/user": { - "Attribute": [ - { - "AttributeId": "http://wso2.org/identity/user/username", - "Value": "publicUser", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - }, - "Action": { - "Attribute": [ - { - "AttributeId": "urn:oasis:names:tc:xacml:1.0:action:action-id", - "Value": "view-status", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - }, - "Resource": { - "Attribute": [ - { - "AttributeId": "urn:oasis:names:tc:xacml:1.0:resource:resource-id", - "Value": "index.jsp", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - } - }, - { - "Decision": "Deny", - "Status": { - "StatusCode": { - "Value": "urn:oasis:names:tc:xacml:1.0:status:ok" - } - }, - "Obligations": [ - { - "Id": "fail_to_permit", - "AttributeAssignments": [ - { - "AttributeId": "obligation-id", - "Value": "You can access the resource index.jsp", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - } - ], - "Resource": { - "Attribute": [ - { - "AttributeId": "urn:oasis:names:tc:xacml:1.0:resource:resource-id", - "Value": "index.jsp", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - }, - "http://wso2.org/identity/user": { - "Attribute": [ - { - "AttributeId": "http://wso2.org/identity/user/username", - "Value": "adminUser", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - }, - "Action": { - "Attribute": [ - { - "AttributeId": "urn:oasis:names:tc:xacml:1.0:action:action-id", - "Value": "view-welcome", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - } - }, - { - "Decision": "Deny", - "Status": { - "StatusCode": { - "Value": "urn:oasis:names:tc:xacml:1.0:status:ok" - } - }, - "Obligations": [ - { - "Id": "fail_to_permit", - "AttributeAssignments": [ - { - "AttributeId": "obligation-id", - "Value": "You can access the resource index.jsp", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - } - ], - "Action": { - "Attribute": [ - { - "AttributeId": "urn:oasis:names:tc:xacml:1.0:action:action-id", - "Value": "modify-welcome", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - }, - "Resource": { - "Attribute": [ - { - "AttributeId": "urn:oasis:names:tc:xacml:1.0:resource:resource-id", - "Value": "index.jsp", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - }, - "http://wso2.org/identity/user": { - "Attribute": [ - { - "AttributeId": "http://wso2.org/identity/user/username", - "Value": "publicUser", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - } - } - ] -} diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/entitlement/json/simpleMDPRequest.json b/modules/integration/tests-integration/tests-backend/src/test/resources/entitlement/json/simpleMDPRequest.json deleted file mode 100644 index d690d4a7f72..00000000000 --- a/modules/integration/tests-integration/tests-backend/src/test/resources/entitlement/json/simpleMDPRequest.json +++ /dev/null @@ -1,63 +0,0 @@ -{ - "Request": { - "http://wso2.org/identity/user": [ - { - "Attribute": [ - { - "AttributeId": "http://wso2.org/identity/user/username", - "Value": "adminUser", - "IncludeInResult": true, - "DataType": "string" - } - ] - },{ - "Attribute": [ - { - "AttributeId": "http://wso2.org/identity/user/username", - "Value": "internalUser", - "IncludeInResult": true, - "DataType": "string" - } - ] - } ], - - "Resource": { - "Attribute": [ - { - "AttributeId": "resource-id", - "Value": "index.jsp", - "IncludeInResult": false - } - ] - }, - "Action": [{ - "Attribute": [{ - "AttributeId": "action-id", - "Value": "view-welcome", - "IncludeInResult": true - } - ] - },{ - "Attribute": [{ - "AttributeId": "action-id", - "Value": "view-status", - "IncludeInResult": false - } - ] - },{ - "Attribute": [{ - "AttributeId": "action-id", - "Value": "view-summary", - "IncludeInResult": true - } - ] - },{ - "Attribute": [{ - "AttributeId": "action-id", - "Value": "modify-welcome", - "IncludeInResult": true - } - ] - } ] - } -} diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/entitlement/json/simpleMDPResponse.json b/modules/integration/tests-integration/tests-backend/src/test/resources/entitlement/json/simpleMDPResponse.json deleted file mode 100644 index 9c5072a2c7f..00000000000 --- a/modules/integration/tests-integration/tests-backend/src/test/resources/entitlement/json/simpleMDPResponse.json +++ /dev/null @@ -1,280 +0,0 @@ -{ - "Response": [ - { - "Decision": "Deny", - "Status": { - "StatusCode": { - "Value": "urn:oasis:names:tc:xacml:1.0:status:ok" - } - }, - "Obligations": [ - { - "Id": "fail_to_permit", - "AttributeAssignments": [ - { - "AttributeId": "obligation-id", - "Value": "You can access the resource index.jsp", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - } - ], - "http://wso2.org/identity/user": { - "Attribute": [ - { - "AttributeId": "http://wso2.org/identity/user/username", - "Value": "internalUser", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - }, - "Action": { - "Attribute": [ - { - "AttributeId": "urn:oasis:names:tc:xacml:1.0:action:action-id", - "Value": "view-welcome", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - } - }, - { - "Decision": "Permit", - "Status": { - "StatusCode": { - "Value": "urn:oasis:names:tc:xacml:1.0:status:ok" - } - }, - "http://wso2.org/identity/user": { - "Attribute": [ - { - "AttributeId": "http://wso2.org/identity/user/username", - "Value": "internalUser", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - } - }, - { - "Decision": "Deny", - "Status": { - "StatusCode": { - "Value": "urn:oasis:names:tc:xacml:1.0:status:ok" - } - }, - "Obligations": [ - { - "Id": "fail_to_permit", - "AttributeAssignments": [ - { - "AttributeId": "obligation-id", - "Value": "You can access the resource index.jsp", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - } - ], - "Action": { - "Attribute": [ - { - "AttributeId": "urn:oasis:names:tc:xacml:1.0:action:action-id", - "Value": "view-summary", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - }, - "http://wso2.org/identity/user": { - "Attribute": [ - { - "AttributeId": "http://wso2.org/identity/user/username", - "Value": "adminUser", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - } - }, - { - "Decision": "Deny", - "Status": { - "StatusCode": { - "Value": "urn:oasis:names:tc:xacml:1.0:status:ok" - } - }, - "Obligations": [ - { - "Id": "fail_to_permit", - "AttributeAssignments": [ - { - "AttributeId": "obligation-id", - "Value": "You can access the resource index.jsp", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - } - ], - "Action": { - "Attribute": [ - { - "AttributeId": "urn:oasis:names:tc:xacml:1.0:action:action-id", - "Value": "view-summary", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - }, - "http://wso2.org/identity/user": { - "Attribute": [ - { - "AttributeId": "http://wso2.org/identity/user/username", - "Value": "internalUser", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - } - }, - { - "Decision": "Deny", - "Status": { - "StatusCode": { - "Value": "urn:oasis:names:tc:xacml:1.0:status:ok" - } - }, - "Obligations": [ - { - "Id": "fail_to_permit", - "AttributeAssignments": [ - { - "AttributeId": "obligation-id", - "Value": "You can access the resource index.jsp", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - } - ], - "http://wso2.org/identity/user": { - "Attribute": [ - { - "AttributeId": "http://wso2.org/identity/user/username", - "Value": "adminUser", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - }, - "Action": { - "Attribute": [ - { - "AttributeId": "urn:oasis:names:tc:xacml:1.0:action:action-id", - "Value": "view-welcome", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - } - }, - { - "Decision": "Deny", - "Status": { - "StatusCode": { - "Value": "urn:oasis:names:tc:xacml:1.0:status:ok" - } - }, - "Obligations": [ - { - "Id": "fail_to_permit", - "AttributeAssignments": [ - { - "AttributeId": "obligation-id", - "Value": "You can access the resource index.jsp", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - } - ], - "http://wso2.org/identity/user": { - "Attribute": [ - { - "AttributeId": "http://wso2.org/identity/user/username", - "Value": "internalUser", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - }, - "Action": { - "Attribute": [ - { - "AttributeId": "urn:oasis:names:tc:xacml:1.0:action:action-id", - "Value": "modify-welcome", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - } - }, - { - "Decision": "Permit", - "Status": { - "StatusCode": { - "Value": "urn:oasis:names:tc:xacml:1.0:status:ok" - } - }, - "http://wso2.org/identity/user": { - "Attribute": [ - { - "AttributeId": "http://wso2.org/identity/user/username", - "Value": "adminUser", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - }, - "Action": { - "Attribute": [ - { - "AttributeId": "urn:oasis:names:tc:xacml:1.0:action:action-id", - "Value": "modify-welcome", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - } - }, - { - "Decision": "Deny", - "Status": { - "StatusCode": { - "Value": "urn:oasis:names:tc:xacml:1.0:status:ok" - } - }, - "Obligations": [ - { - "Id": "fail_to_permit", - "AttributeAssignments": [ - { - "AttributeId": "obligation-id", - "Value": "You can access the resource index.jsp", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - } - ], - "http://wso2.org/identity/user": { - "Attribute": [ - { - "AttributeId": "http://wso2.org/identity/user/username", - "Value": "adminUser", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - } - } - ] -} diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/entitlement/json/simpleRequest.json b/modules/integration/tests-integration/tests-backend/src/test/resources/entitlement/json/simpleRequest.json deleted file mode 100644 index 6f42054a9a2..00000000000 --- a/modules/integration/tests-integration/tests-backend/src/test/resources/entitlement/json/simpleRequest.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "Request": { - "http://wso2.org/identity/user": { - "Attribute": [ - { - "AttributeId": "http://wso2.org/identity/user/username", - "Value": "adminUser", - "DataType": "string", - "IncludeInResult": true - } - ] - }, - - "Resource": { - "Attribute": [ - { - "AttributeId": "resource-id", - "Value": "index.jsp", - "DataType": "string", - "IncludeInResult": true - } - ] - }, - "Action": { - "Attribute": [{ - "AttributeId": "action-id", - "Value": "view-welcome", - "DataType": "string", - "IncludeInResult": true - } - ] - } - - } -} diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/entitlement/json/simpleResponse.json b/modules/integration/tests-integration/tests-backend/src/test/resources/entitlement/json/simpleResponse.json deleted file mode 100644 index b007152e9b1..00000000000 --- a/modules/integration/tests-integration/tests-backend/src/test/resources/entitlement/json/simpleResponse.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "Response": [ - { - "Decision": "Deny", - "Status": { - "StatusCode": { - "Value": "urn:oasis:names:tc:xacml:1.0:status:ok" - } - }, - "Obligations": [ - { - "Id": "fail_to_permit", - "AttributeAssignments": [ - { - "AttributeId": "obligation-id", - "Value": "You can access the resource index.jsp", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - } - ], - "http://wso2.org/identity/user": { - "Attribute": [ - { - "AttributeId": "http://wso2.org/identity/user/username", - "Value": "adminUser", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - }, - "Action": { - "Attribute": [ - { - "AttributeId": "urn:oasis:names:tc:xacml:1.0:action:action-id", - "Value": "view-welcome", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - }, - "Resource": { - "Attribute": [ - { - "AttributeId": "urn:oasis:names:tc:xacml:1.0:resource:resource-id", - "Value": "index.jsp", - "IncludeInResult": "true", - "DataType": "http://www.w3.org/2001/XMLSchema#string" - } - ] - } - } - ] -} diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/identity.xml b/modules/integration/tests-integration/tests-backend/src/test/resources/identity.xml index d2efc4a04cc..822db2edbc9 100755 --- a/modules/integration/tests-integration/tests-backend/src/test/resources/identity.xml +++ b/modules/integration/tests-integration/tests-backend/src/test/resources/identity.xml @@ -100,7 +100,6 @@ - diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/org/wso2/identity/integration/test/rest/api/server/application/management/v1/oidc-metadata.json b/modules/integration/tests-integration/tests-backend/src/test/resources/org/wso2/identity/integration/test/rest/api/server/application/management/v1/oidc-metadata.json index cb0fe21e917..2449617dd60 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/resources/org/wso2/identity/integration/test/rest/api/server/application/management/v1/oidc-metadata.json +++ b/modules/integration/tests-integration/tests-backend/src/test/resources/org/wso2/identity/integration/test/rest/api/server/application/management/v1/oidc-metadata.json @@ -74,8 +74,7 @@ }, "scopeValidators": { "options": [ - "Role based scope validator", - "XACML Scope Validator" + "Role based scope validator" ] }, "accessTokenType": { diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/org/wso2/identity/integration/test/rest/api/server/claim/management/v1/claim-management-add-external-claim-already-mapped.json b/modules/integration/tests-integration/tests-backend/src/test/resources/org/wso2/identity/integration/test/rest/api/server/claim/management/v1/claim-management-add-external-claim-already-mapped.json new file mode 100644 index 00000000000..39b7d25b462 --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/resources/org/wso2/identity/integration/test/rest/api/server/claim/management/v1/claim-management-add-external-claim-already-mapped.json @@ -0,0 +1,4 @@ +{ + "claimURI": "http://dummy.org/claim/email", + "mappedLocalClaimURI": "http://wso2.org/claims/emailaddress" +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/org/wso2/identity/integration/test/rest/api/server/claim/management/v1/claim-management-add-external-claim-mapped-to-custom-local-claim.json b/modules/integration/tests-integration/tests-backend/src/test/resources/org/wso2/identity/integration/test/rest/api/server/claim/management/v1/claim-management-add-external-claim-mapped-to-custom-local-claim.json new file mode 100644 index 00000000000..fa63f4cb701 --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/resources/org/wso2/identity/integration/test/rest/api/server/claim/management/v1/claim-management-add-external-claim-mapped-to-custom-local-claim.json @@ -0,0 +1,4 @@ +{ + "claimURI": "http://updateddummy.org/claim/emailaddress", + "mappedLocalClaimURI": "http://wso2.org/claims/dummyemailaddress" +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/org/wso2/identity/integration/test/rest/api/server/claim/management/v1/claim-management-add-local-claim-with-existing-uri.json b/modules/integration/tests-integration/tests-backend/src/test/resources/org/wso2/identity/integration/test/rest/api/server/claim/management/v1/claim-management-add-local-claim-with-existing-uri.json new file mode 100644 index 00000000000..e0a2ba5205a --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/resources/org/wso2/identity/integration/test/rest/api/server/claim/management/v1/claim-management-add-local-claim-with-existing-uri.json @@ -0,0 +1,21 @@ +{ + "claimURI": "http://wso2.org/claims/fullname", + "description": "Full Name Duplicate", + "displayOrder": 4, + "displayName": "Full Name Duplicate", + "readOnly": false, + "required": true, + "supportedByDefault": true, + "attributeMapping": [ + { + "mappedAttribute": "fullname", + "userstore": "PRIMARY" + } + ], + "properties": [ + { + "key": "isVerifiable", + "value": "false" + } + ] +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/org/wso2/identity/integration/test/rest/api/server/claim/management/v1/claim-management-update-default-external-claim.json b/modules/integration/tests-integration/tests-backend/src/test/resources/org/wso2/identity/integration/test/rest/api/server/claim/management/v1/claim-management-update-default-external-claim.json new file mode 100644 index 00000000000..3fbf744a648 --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/resources/org/wso2/identity/integration/test/rest/api/server/claim/management/v1/claim-management-update-default-external-claim.json @@ -0,0 +1,4 @@ +{ + "claimURI": "urn:ietf:params:scim:schemas:core:2.0:meta.resourceType", + "mappedLocalClaimURI": "http://wso2.org/claims/userType" +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/org/wso2/identity/integration/test/rest/api/server/claim/management/v1/claim-management-update-external-claim-already-mapped.json b/modules/integration/tests-integration/tests-backend/src/test/resources/org/wso2/identity/integration/test/rest/api/server/claim/management/v1/claim-management-update-external-claim-already-mapped.json new file mode 100644 index 00000000000..6f47f0e7a0d --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/resources/org/wso2/identity/integration/test/rest/api/server/claim/management/v1/claim-management-update-external-claim-already-mapped.json @@ -0,0 +1,4 @@ +{ + "claimURI": "address", + "mappedLocalClaimURI": "http://wso2.org/claims/addresses.formatted" +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/org/wso2/identity/integration/test/rest/api/server/claim/management/v1/claim-management-update-external-claim-invalid-mapped-claim.json b/modules/integration/tests-integration/tests-backend/src/test/resources/org/wso2/identity/integration/test/rest/api/server/claim/management/v1/claim-management-update-external-claim-invalid-mapped-claim.json new file mode 100644 index 00000000000..4d9220ff90f --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/resources/org/wso2/identity/integration/test/rest/api/server/claim/management/v1/claim-management-update-external-claim-invalid-mapped-claim.json @@ -0,0 +1,4 @@ +{ + "claimURI": "http://updateddummy.org/claim/emailaddress", + "mappedLocalClaimURI": "http://wso2.org/claims/dummyclaim" +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/org/wso2/identity/integration/test/rest/api/server/idp/v1/add-idp-oidc-standard-based.json b/modules/integration/tests-integration/tests-backend/src/test/resources/org/wso2/identity/integration/test/rest/api/server/idp/v1/add-idp-oidc-standard-based.json new file mode 100644 index 00000000000..1d5831d2577 --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/resources/org/wso2/identity/integration/test/rest/api/server/idp/v1/add-idp-oidc-standard-based.json @@ -0,0 +1,61 @@ +{ + "name": "OIDC IdP", + "alias": "", + "description": "Authenticate users with Enterprise OIDC connections.", + "image": "assets/images/logos/enterprise.svg", + "isPrimary": false, + "roles": { + "mappings": [], + "outboundProvisioningRoles": [] + }, + "certificate": { + "jwksUri": "https://test.com/jwks", + "certificates": [ + "" + ] + }, + "claims": { + "userIdClaim": { + "uri": "" + }, + "provisioningClaims": [], + "roleClaim": { + "uri": "" + } + }, + "federatedAuthenticators": { + "defaultAuthenticatorId": "T3BlbklEQ29ubmVjdEF1dGhlbnRpY2F0b3I", + "authenticators": [ + { + "isEnabled": true, + "authenticatorId": "T3BlbklEQ29ubmVjdEF1dGhlbnRpY2F0b3I", + "properties": [ + { + "key": "ClientId", + "value": "abcd1234wxyz5678ijklmnopqrst9012" + }, + { + "key": "ClientSecret", + "value": "mnop3456qrst1234uvwx5678abcd9012" + }, + { + "key": "OAuth2AuthzEPUrl", + "value": "https://test.com/authz" + }, + { + "key": "OAuth2TokenEPUrl", + "value": "https://test.com/token" + }, + { + "key": "callbackUrl", + "value": "https://test.com/commonauth" + } + ] + } + ] + }, + "homeRealmIdentifier": "", + "isFederationHub": false, + "idpIssuerName": "", + "templateId": "enterprise-oidc-idp" +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/org/wso2/identity/integration/test/rest/api/server/idp/v1/add-idp-with-custom-fed-auth.json b/modules/integration/tests-integration/tests-backend/src/test/resources/org/wso2/identity/integration/test/rest/api/server/idp/v1/add-idp-with-custom-fed-auth.json new file mode 100644 index 00000000000..1252d7a50d3 --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/resources/org/wso2/identity/integration/test/rest/api/server/idp/v1/add-idp-with-custom-fed-auth.json @@ -0,0 +1,38 @@ +{ + "name": "", + "description": "IdP with user defined federated authenticator", + "image": "https://example.com/image", + "isPrimary": false, + "isFederationHub": false, + "homeRealmIdentifier": "localhost", + "alias": "https://localhost:9444/oauth2/token", + "claims": { + "userIdClaim": { + "uri": "http://wso2.org/claims/username" + }, + "roleClaim": { + "uri": "http://wso2.org/claims/role" + }, + "provisioningClaims": [ + { + "claim": { + "uri": "http://wso2.org/claims/username" + }, + "defaultValue": "sathya" + } + ] + }, + "federatedAuthenticators": { + "defaultAuthenticatorId": "", + "authenticators": [ + "" + ] + }, + "provisioning": { + "jit": { + "isEnabled": true, + "scheme": "PROVISION_SILENTLY", + "userstore": "PRIMARY" + } + } +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/org/wso2/identity/integration/test/rest/api/server/idp/v1/add-idp-with-custom-fed-multi-auth.json b/modules/integration/tests-integration/tests-backend/src/test/resources/org/wso2/identity/integration/test/rest/api/server/idp/v1/add-idp-with-custom-fed-multi-auth.json new file mode 100644 index 00000000000..99766937919 --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/resources/org/wso2/identity/integration/test/rest/api/server/idp/v1/add-idp-with-custom-fed-multi-auth.json @@ -0,0 +1,39 @@ +{ + "name": "", + "description": "IdP with user defined federated authenticator", + "image": "https://example.com/image", + "isPrimary": false, + "isFederationHub": false, + "homeRealmIdentifier": "localhost", + "alias": "https://localhost:9444/oauth2/token", + "claims": { + "userIdClaim": { + "uri": "http://wso2.org/claims/username" + }, + "roleClaim": { + "uri": "http://wso2.org/claims/role" + }, + "provisioningClaims": [ + { + "claim": { + "uri": "http://wso2.org/claims/username" + }, + "defaultValue": "sathya" + } + ] + }, + "federatedAuthenticators": { + "defaultAuthenticatorId": "", + "authenticators": [ + "", + "" + ] + }, + "provisioning": { + "jit": { + "isEnabled": true, + "scheme": "PROVISION_SILENTLY", + "userstore": "PRIMARY" + } + } +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/org/wso2/identity/integration/test/rest/api/server/idp/v1/update-idp-oidc-standard-based-duplicated-scopes.json b/modules/integration/tests-integration/tests-backend/src/test/resources/org/wso2/identity/integration/test/rest/api/server/idp/v1/update-idp-oidc-standard-based-duplicated-scopes.json new file mode 100644 index 00000000000..701256b2539 --- /dev/null +++ b/modules/integration/tests-integration/tests-backend/src/test/resources/org/wso2/identity/integration/test/rest/api/server/idp/v1/update-idp-oidc-standard-based-duplicated-scopes.json @@ -0,0 +1,15 @@ +{ + "authenticatorId": "T3BlbklEQ29ubmVjdEF1dGhlbnRpY2F0b3I", + "isEnabled": true, + "isDefault": true, + "properties": [ + { + "key": "commonAuthQueryParams", + "value": "scope=openid country profile" + }, + { + "key": "Scopes", + "value": "openid country profile" + } + ] +} diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/spFile/TestServer.xml b/modules/integration/tests-integration/tests-backend/src/test/resources/spFile/TestServer.xml index 6b990ae12ac..01de5f25e52 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/resources/spFile/TestServer.xml +++ b/modules/integration/tests-integration/tests-backend/src/test/resources/spFile/TestServer.xml @@ -77,7 +77,6 @@ refresh_token urn:ietf:params:oauth:grant-type:saml2-bearer implicit password client_credentials iwa:ntlm authorization_code urn:ietf:params:oauth:grant-type:jwt-bearer Role based scope validator - XACML Scope Validator true false diff --git a/modules/integration/tests-integration/tests-backend/src/test/resources/testng.xml b/modules/integration/tests-integration/tests-backend/src/test/resources/testng.xml index 20df6841630..35a8233cdb8 100644 --- a/modules/integration/tests-integration/tests-backend/src/test/resources/testng.xml +++ b/modules/integration/tests-integration/tests-backend/src/test/resources/testng.xml @@ -77,28 +77,17 @@ - - - - - - - - - - - @@ -112,7 +101,6 @@ - @@ -140,13 +128,20 @@ - - - + + + + + + + + + + @@ -245,6 +240,8 @@ + + @@ -376,6 +373,7 @@ + @@ -414,7 +412,6 @@ - diff --git a/modules/integration/tests-ui-integration/src/test/java/org/wso2/identity/ui/integration/test/policy/ui/SimplePolicyEditorTestCase.java b/modules/integration/tests-ui-integration/src/test/java/org/wso2/identity/ui/integration/test/policy/ui/SimplePolicyEditorTestCase.java deleted file mode 100644 index 7cad26a5f5b..00000000000 --- a/modules/integration/tests-ui-integration/src/test/java/org/wso2/identity/ui/integration/test/policy/ui/SimplePolicyEditorTestCase.java +++ /dev/null @@ -1,93 +0,0 @@ -package org.wso2.identity.ui.integration.test.policy.ui; - -import org.openqa.selenium.By; -import org.openqa.selenium.WebDriver; -import org.openqa.selenium.WebElement; -import org.openqa.selenium.support.ui.Select; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.wso2.carbon.automation.extensions.selenium.BrowserManager; -import org.wso2.identity.integration.common.ui.page.LoginPage; -import org.wso2.identity.integration.common.ui.page.util.UIElementMapper; -import org.wso2.identity.integration.common.utils.ISIntegrationUITest; - -/** - * - */ - -/** - * @author wso2 - * - */ -public class SimplePolicyEditorTestCase extends ISIntegrationUITest { - - private WebDriver driver; - private UIElementMapper uiElementMapper; - - @BeforeClass(alwaysRun = true) - public void setUp() throws Exception { - super.init(); - driver = BrowserManager.getWebDriver(); - - driver.get(getLoginURL()); - //ToDO migrate to new test environment -// EnvironmentBuilder builder = new EnvironmentBuilder().is(5); -// EnvironmentVariables environment =builder.build().getIs(); - - } - - @Test(groups = "wso2.is", description = "verify last deny rule in simple policy editor") - public void testPolicyCreate() throws Exception { - - LoginPage test = new LoginPage(driver); - test.loginAs("admin", "admin"); - - System.out.println(" *********** Running test policy create ********** "); - this.uiElementMapper = UIElementMapper.getInstance(); - - driver.findElement(By.linkText("Policy Administration")).click(); - driver.findElement(By.linkText("Add New Entitlement Policy")).click(); - driver.findElement(By.linkText("Simple Policy Editor")).click(); - - driver.findElement(By.id("policyId")).sendKeys("policy1"); - driver.findElement(By.id("policyDescription")).sendKeys("Test Description"); - - WebElement dropDownListBox = driver.findElement(By.id("policyApplied")); - Select clickThis = new Select(dropDownListBox); - clickThis.selectByVisibleText("Subject"); - - WebElement dropDownListBox2 = driver.findElement(By.id("userAttributeId")); - Select clickThis2 = new Select(dropDownListBox2); - clickThis2.selectByVisibleText("Role"); - - driver.findElement(By.id("userAttributeValue")).sendKeys("testRole"); - driver.findElement(By.id("actionRuleValue_0")).sendKeys("read"); - driver.findElement(By.id("resourceRuleValue_0")).sendKeys("Res1"); - - driver.findElement(By.xpath("//*[@id=\"mainTable\"]/tbody/tr[6]/td/input[1]")).click(); - - // click ok button of message box - driver.findElement(By.xpath("/html/body/div[3]/div[2]/button")).click(); - - // View policies... - driver.findElement(By.linkText("Policy Administration")).click(); - driver.findElement(By.linkText("policy1")).click(); - Thread.sleep(3000); - - // Check for Deny-Rule - WebElement frame = driver.findElement(By.xpath("//*[@id=\"frame_raw-policy\"]")); - driver.switchTo().frame(frame); - String contentText = driver.findElement(By.id("content_highlight")).getText(); - Assert.assertNotNull(contentText); - Assert.assertTrue(contentText.contains("")); - driver.close(); - - } - - @AfterClass(alwaysRun = true) - public void tearDown() throws Exception { - driver.quit(); - } -} diff --git a/modules/integration/tests-ui-integration/src/test/resources/artifacts/IS/IIA001Policy.xml b/modules/integration/tests-ui-integration/src/test/resources/artifacts/IS/IIA001Policy.xml deleted file mode 100644 index f40f0c208af..00000000000 --- a/modules/integration/tests-ui-integration/src/test/resources/artifacts/IS/IIA001Policy.xml +++ /dev/null @@ -1,68 +0,0 @@ - - - - Policy for Conformance Test IIA001. - - - - - Julius Hibbert can read or write Bart Simpson's medical record. - - - - - - Julius Hibbert - - - - - - - - http://medico.com/record/patient/BartSimpson - - - - - - - - read - - - - - - write - - - - - - - diff --git a/modules/integration/tests-ui-integration/src/test/resources/artifacts/IS/IIA001Request.xml b/modules/integration/tests-ui-integration/src/test/resources/artifacts/IS/IIA001Request.xml deleted file mode 100644 index 5414b78b65b..00000000000 --- a/modules/integration/tests-ui-integration/src/test/resources/artifacts/IS/IIA001Request.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - Julius Hibbert - - - - - http://medico.com/record/patient/BartSimpson - - - - - read - - - - diff --git a/modules/integration/tests-ui-integration/src/test/resources/artifacts/IS/IIA003Policy.xml b/modules/integration/tests-ui-integration/src/test/resources/artifacts/IS/IIA003Policy.xml deleted file mode 100644 index f4829fa597a..00000000000 --- a/modules/integration/tests-ui-integration/src/test/resources/artifacts/IS/IIA003Policy.xml +++ /dev/null @@ -1,70 +0,0 @@ - - - - Policy for Conformance Test IIA003. - - - - - A subject with a "bogus" attribute with a value of - "Physician" can read or write Bart Simpson's medical - record. - - - - - - Physician - - - - - - - - http://medico.com/record/patient/BartSimpson - - - - - - - - read - - - - - - write - - - - - - - diff --git a/modules/integration/tests-ui-integration/src/test/resources/artifacts/IS/IIA003Request.xml b/modules/integration/tests-ui-integration/src/test/resources/artifacts/IS/IIA003Request.xml deleted file mode 100644 index 2dc5861db12..00000000000 --- a/modules/integration/tests-ui-integration/src/test/resources/artifacts/IS/IIA003Request.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - Julius Hibbert - - - - - http://medico.com/record/patient/BartSimpson - - - - - read - - diff --git a/modules/integration/tests-ui-integration/src/test/resources/artifacts/IS/entitlement/policies/policy1.xml b/modules/integration/tests-ui-integration/src/test/resources/artifacts/IS/entitlement/policies/policy1.xml deleted file mode 100644 index 0b8a8be97b4..00000000000 --- a/modules/integration/tests-ui-integration/src/test/resources/artifacts/IS/entitlement/policies/policy1.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - testRole - - - - - - - - - - - read - - - - - - - \ No newline at end of file diff --git a/modules/integration/tests-ui-integration/src/test/resources/artifacts/IS/openId/identity-default.xml b/modules/integration/tests-ui-integration/src/test/resources/artifacts/IS/openId/identity-default.xml index 4d8e3c8842e..5acc7be717f 100644 --- a/modules/integration/tests-ui-integration/src/test/resources/artifacts/IS/openId/identity-default.xml +++ b/modules/integration/tests-ui-integration/src/test/resources/artifacts/IS/openId/identity-default.xml @@ -195,7 +195,6 @@ - diff --git a/modules/integration/tests-ui-integration/src/test/resources/artifacts/IS/openId/identity-skipuserconsent.xml b/modules/integration/tests-ui-integration/src/test/resources/artifacts/IS/openId/identity-skipuserconsent.xml index 169c1725c1f..eda1280af85 100644 --- a/modules/integration/tests-ui-integration/src/test/resources/artifacts/IS/openId/identity-skipuserconsent.xml +++ b/modules/integration/tests-ui-integration/src/test/resources/artifacts/IS/openId/identity-skipuserconsent.xml @@ -195,7 +195,6 @@ - diff --git a/modules/integration/tests-ui-integration/src/test/resources/instrumentation.txt b/modules/integration/tests-ui-integration/src/test/resources/instrumentation.txt index c92960be910..cdbd61dc8c3 100644 --- a/modules/integration/tests-ui-integration/src/test/resources/instrumentation.txt +++ b/modules/integration/tests-ui-integration/src/test/resources/instrumentation.txt @@ -9,8 +9,6 @@ org.wso2.carbon.identity.authorization.core_ org.wso2.carbon.identity.base_ org.wso2.carbon.identity.certificateauthority_ org.wso2.carbon.identity.core_ -org.wso2.carbon.identity.entitlement_ -org.wso2.carbon.identity.entitlement.common_ org.wso2.carbon.identity.mgt_ org.wso2.carbon.identity.oauth_ org.wso2.carbon.identity.oauth.common_ diff --git a/modules/integration/tests-ui-integration/src/test/resources/testng.xml b/modules/integration/tests-ui-integration/src/test/resources/testng.xml index e739b29cf6f..faa3bc5900d 100644 --- a/modules/integration/tests-ui-integration/src/test/resources/testng.xml +++ b/modules/integration/tests-ui-integration/src/test/resources/testng.xml @@ -16,7 +16,6 @@ - diff --git a/modules/local-authenticators/pom.xml b/modules/local-authenticators/pom.xml index 8a35461682c..fd486107350 100644 --- a/modules/local-authenticators/pom.xml +++ b/modules/local-authenticators/pom.xml @@ -19,7 +19,7 @@ org.wso2.is identity-server-parent - 7.1.0-m5-SNAPSHOT + 7.1.0-m6-SNAPSHOT ../../pom.xml 4.0.0 diff --git a/modules/oauth2-grant-types/pom.xml b/modules/oauth2-grant-types/pom.xml index 57cdd2493f1..b1eb0b673b2 100644 --- a/modules/oauth2-grant-types/pom.xml +++ b/modules/oauth2-grant-types/pom.xml @@ -19,7 +19,7 @@ org.wso2.is identity-server-parent - 7.1.0-m5-SNAPSHOT + 7.1.0-m6-SNAPSHOT ../../pom.xml diff --git a/modules/p2-profile-gen/carbon.product b/modules/p2-profile-gen/carbon.product index badb2b403cf..e1a60d0d981 100644 --- a/modules/p2-profile-gen/carbon.product +++ b/modules/p2-profile-gen/carbon.product @@ -2,7 +2,7 @@ +version="4.10.27" useFeatures="true" includeLaunchers="true"> @@ -14,7 +14,7 @@ version="4.10.24" useFeatures="true" includeLaunchers="true"> - + diff --git a/modules/p2-profile-gen/pom.xml b/modules/p2-profile-gen/pom.xml index 2aa77f4cbed..caa6a56ac84 100644 --- a/modules/p2-profile-gen/pom.xml +++ b/modules/p2-profile-gen/pom.xml @@ -19,7 +19,7 @@ org.wso2.is identity-server-parent - 7.1.0-m5-SNAPSHOT + 7.1.0-m6-SNAPSHOT ../../pom.xml @@ -188,9 +188,6 @@ org.wso2.carbon.identity.framework:org.wso2.carbon.identity.user.profile.feature:${carbon.identity.framework.version} - - org.wso2.carbon.identity.framework:org.wso2.carbon.identity.xacml.feature:${carbon.identity.framework.version} - org.wso2.carbon.identity.framework:org.wso2.carbon.claim.mgt.feature:${carbon.identity.framework.version} @@ -221,12 +218,6 @@ org.wso2.carbon.identity.framework:org.wso2.carbon.identity.application.authentication.framework.server.feature:${carbon.identity.framework.version} - - org.wso2.carbon.identity.application.authz.xacml:org.wso2.carbon.identity.application.authz.xacml.server.feature:${identity.app.authz.xacml.version} - - - org.wso2.carbon.extension.identity.oauth.addons:org.wso2.carbon.identity.oauth2.validators.xacml.server.feature:${identity.oauth.addons.version} - org.wso2.carbon.identity.datapublisher.authentication:org.wso2.carbon.identity.data.publisher.application.authentication.server.feature:${identity.data.publisher.authentication.version} @@ -371,6 +362,11 @@ org.wso2.carbon.identity.framework:org.wso2.carbon.identity.certificate.management.server.feature:${carbon.identity.framework.version} + + + org.wso2.carbon.identity.framework:org.wso2.carbon.identity.rule.management.server.feature:${carbon.identity.framework.version} + + org.wso2.carbon.identity.tool.validator.sso.saml2:org.wso2.carbon.identity.tools.saml.validator.feature:${identity.tool.samlsso.validator.version} @@ -694,10 +690,6 @@ org.wso2.carbon.identity.user.profile.feature.group ${carbon.identity.framework.version} - - org.wso2.carbon.identity.xacml.feature.group - ${carbon.identity.framework.version} - org.wso2.carbon.identity.sso.saml.feature.group ${identity.inbound.auth.saml.version} @@ -869,6 +861,10 @@ org.wso2.carbon.identity.certificate.management.server.feature.group ${carbon.identity.framework.version} + + org.wso2.carbon.identity.rule.management.server.feature.group + ${carbon.identity.framework.version} + org.wso2.carbon.identity.unique.claim.mgt.server.feature.group @@ -932,18 +928,6 @@ ${identity.apps.core.version} - - - org.wso2.carbon.identity.application.authz.xacml.server.feature.group - - ${identity.app.authz.xacml.version} - - - - org.wso2.carbon.identity.oauth2.validators.xacml.server.feature.group - - ${identity.oauth.addons.version} - org.wso2.carbon.identity.data.publisher.application.authentication.server.feature.group diff --git a/modules/provisioning-connectors/pom.xml b/modules/provisioning-connectors/pom.xml index a9634438b2a..ed021f26c51 100644 --- a/modules/provisioning-connectors/pom.xml +++ b/modules/provisioning-connectors/pom.xml @@ -19,7 +19,7 @@ org.wso2.is identity-server-parent - 7.1.0-m5-SNAPSHOT + 7.1.0-m6-SNAPSHOT ../../pom.xml 4.0.0 diff --git a/modules/social-authenticators/pom.xml b/modules/social-authenticators/pom.xml index d62695d8c69..286a14ed4a3 100644 --- a/modules/social-authenticators/pom.xml +++ b/modules/social-authenticators/pom.xml @@ -19,7 +19,7 @@ org.wso2.is identity-server-parent - 7.1.0-m5-SNAPSHOT + 7.1.0-m6-SNAPSHOT ../../pom.xml 4.0.0 diff --git a/modules/styles/pom.xml b/modules/styles/pom.xml index 1096948d905..b61cd18d5e4 100644 --- a/modules/styles/pom.xml +++ b/modules/styles/pom.xml @@ -20,7 +20,7 @@ org.wso2.is identity-server-parent - 7.1.0-m5-SNAPSHOT + 7.1.0-m6-SNAPSHOT ../../pom.xml diff --git a/modules/styles/product/pom.xml b/modules/styles/product/pom.xml index f76a9291070..48b2c689457 100644 --- a/modules/styles/product/pom.xml +++ b/modules/styles/product/pom.xml @@ -20,7 +20,7 @@ org.wso2.is identity-server-styles-parent - 7.1.0-m5-SNAPSHOT + 7.1.0-m6-SNAPSHOT ../pom.xml diff --git a/modules/tests-utils/admin-services/pom.xml b/modules/tests-utils/admin-services/pom.xml index 028ab40b9ff..649145d8a74 100644 --- a/modules/tests-utils/admin-services/pom.xml +++ b/modules/tests-utils/admin-services/pom.xml @@ -19,7 +19,7 @@ org.wso2.is identity-integration-tests-utils - 7.1.0-m5-SNAPSHOT + 7.1.0-m6-SNAPSHOT ../pom.xml diff --git a/modules/tests-utils/admin-stubs/pom.xml b/modules/tests-utils/admin-stubs/pom.xml index 07b0b1ceb90..9b3886fb271 100644 --- a/modules/tests-utils/admin-stubs/pom.xml +++ b/modules/tests-utils/admin-stubs/pom.xml @@ -21,7 +21,7 @@ org.wso2.is identity-integration-tests-utils - 7.1.0-m5-SNAPSHOT + 7.1.0-m6-SNAPSHOT ../pom.xml diff --git a/modules/tests-utils/pom.xml b/modules/tests-utils/pom.xml index e5cfb809123..9eec7159013 100644 --- a/modules/tests-utils/pom.xml +++ b/modules/tests-utils/pom.xml @@ -19,7 +19,7 @@ org.wso2.is identity-server-parent - 7.1.0-m5-SNAPSHOT + 7.1.0-m6-SNAPSHOT ../../pom.xml diff --git a/pom.xml b/pom.xml index daf13926dcb..3c9b135abaf 100755 --- a/pom.xml +++ b/pom.xml @@ -28,7 +28,7 @@ identity-server-parent pom WSO2 Identity Server - 7.1.0-m5-SNAPSHOT + 7.1.0-m6-SNAPSHOT WSO2 Identity Server http://wso2.org/projects/identity @@ -954,16 +954,6 @@ org.wso2.carbon.authenticator.stub ${carbon.kernel.version} - - org.wso2.carbon.identity.framework - org.wso2.carbon.identity.entitlement - ${carbon.identity.framework.version} - - - org.wso2.carbon.identity.framework - org.wso2.carbon.identity.entitlement.stub - ${carbon.identity.framework.version} - org.wso2.securevault org.wso2.securevault @@ -1828,17 +1818,6 @@ org.wso2.identity.apps.x509certificate.portal.server.feature ${identity.apps.core.version} - - - org.wso2.carbon.identity.application.authz.xacml - org.wso2.carbon.identity.application.authz.xacml.server.feature - ${identity.app.authz.xacml.version} - - - org.wso2.carbon.extension.identity.oauth.addons - org.wso2.carbon.identity.oauth2.validators.xacml.server.feature - ${identity.oauth.addons.version} - org.wso2.carbon.identity.outbound.auth.oauth2 org.wso2.carbon.identity.outbound.auth.oauth2.server.feature @@ -2305,6 +2284,18 @@ ${identity.integration.ui.templates.version} zip + + org.wso2.carbon.identity.integration.ui.templates + org.wso2.carbon.identity.integration.ui.templates.applications.zoom + ${identity.integration.ui.templates.version} + zip + + + org.wso2.carbon.identity.integration.ui.templates + org.wso2.carbon.identity.integration.ui.templates.applications.slack + ${identity.integration.ui.templates.version} + zip + @@ -2365,49 +2356,49 @@ - 7.5.115 + 7.7.23 [5.14.67, 8.0.0) - 1.4.1 + 1.4.2 [1.0.0,2.0.0) - 2.6.3 + 2.6.4 - 1.11.13 + 1.11.20 - 5.9.5 + 5.9.8 5.5.0 - 5.5.1 - 1.9.13 + 5.5.2 + 1.9.14 - 7.0.180 - 5.11.45 + 7.0.195 + 5.11.47 5.10.2 - 5.11.12 + 5.11.13 5.7.7 - 3.4.98 + 3.4.102 - 5.5.10 - 5.8.4 + 5.5.11 + 5.8.7 5.2.5 - 5.7.1 - 1.7.3 - 1.4.5 + 5.7.4 + 1.7.4 + 1.4.6 - 1.9.12 - 1.9.14 + 1.9.13 + 1.9.26 @@ -2423,25 +2414,25 @@ 5.5.6 - 5.2.14 + 5.2.15 5.2.15 5.2.3 1.0.6 1.1.14 - 5.2.4 - 5.2.7 - 5.3.3 - 2.0.6 + 5.2.5 + 5.2.9 + 5.3.5 + 2.0.7 - 6.8.15 - 5.4.15 - 5.4.7 + 6.8.18 + 5.4.16 + 5.4.8 - 3.0.2 + 3.0.3 2.3.2 @@ -2455,67 +2446,66 @@ 0.0.20 2.1.3 3.3.31 - 1.1.28 + 1.1.29 4.1.30 1.0.24 - 1.0.9 + 1.0.13 1.1.2 - 3.1.22 - 1.0.19 - 1.0.7 + 3.1.24 + 1.0.21 + 1.0.8 - 1.4.52 - 1.1.17 - 1.1.38 - 1.1.26 + 1.4.59 + 1.1.19 + 1.1.42 + 1.1.27 0.1.7 - 1.1.16 + 1.1.17 2.0.17 - 1.2.247 - 1.3.44 + 1.3.6 + 1.3.46 5.5.9 - 5.5.9 - 2.3.2 - 2.5.17 + 5.5.10 + 2.5.19 1.1.13 - 1.2.66 + 1.2.69 - 2.34.18 - 2.12.16 - 2.7.3 + 2.35.22 + 2.13.28 + 2.8.5 1.6.378 3.4.1 - 4.10.24 + 4.10.27 - 1.0.13 + 1.0.15 - 4.12.29 + 4.12.30 4.10.13 - 4.8.38 - 4.11.29 + 4.8.39 + 4.11.31 1.3.12 - 5.2.59 + 5.2.61 2.0.27 - 2.1.7 + 2.2.2 1.3.0 1.1.26 - 1.1.9 + 1.1.10 2.2.1 @@ -2599,7 +2589,7 @@ 2.6.0.wso2v1 - 4.4.12 + 4.4.13 4.5.4 2.40.0 6.1.1 @@ -2634,7 +2624,7 @@ my-scm-server - 1.0.10 + 1.0.11 2.0.1 2.0.1 diff --git a/product-scenarios/scenarios-commons/src/main/java/org/wso2/identity/scenarios/commons/security/SSOAgentX509KeyStoreCredential.java b/product-scenarios/scenarios-commons/src/main/java/org/wso2/identity/scenarios/commons/security/SSOAgentX509KeyStoreCredential.java index f851937f32c..907fe14ef0e 100644 --- a/product-scenarios/scenarios-commons/src/main/java/org/wso2/identity/scenarios/commons/security/SSOAgentX509KeyStoreCredential.java +++ b/product-scenarios/scenarios-commons/src/main/java/org/wso2/identity/scenarios/commons/security/SSOAgentX509KeyStoreCredential.java @@ -98,7 +98,7 @@ protected void readX509Credentials(InputStream keyStoreInputStream, char[] keySt char[] privateKeyPassword) throws Exception { try { - KeyStore keyStore = KeyStore.getInstance("PKCS12"); + KeyStore keyStore = Keystore.getInstance("PKCS12"); keyStore.load(keyStoreInputStream, keyStorePassword); readX509Credentials(keyStore, publicCertAlias, privateKeyAlias, privateKeyPassword); } catch (Exception e) {
", "