amplify-hosting icon indicating copy to clipboard operation
amplify-hosting copied to clipboard

Preview deploy doesn't update redirect URLs

Open adi-works opened this issue 4 years ago • 4 comments

Before opening, please confirm:

App Id

dazj4he0xk1lv

Region

us-east-1

Amplify Console feature

Previews

Describe the bug

I enabled Previews, created a PR, and deployed it successfully. However, when I go to its URL, it redirects to login and then redirects again with a URL mismatch error, because while initializing the environment, it didn't update the redirect URIs, so Cognito stays outdated, with the configuration it derived from the production environment.

I should point I wasn't able to find an existing issue, which is very odd, given the fact it's a popular feature. I did have to swap out the default amplifyPush with my own (which I simply grabbed from this repository), to overcome issues like a missing Google parameter, failure to find existing environment, etc'.

Expected behavior

Update OAuth redirect URIs with the newly created deploy subdomain URL.

Reproduction steps

  • Enable Previews
  • Deploy

Build Settings

# https://docs.amplify.aws/cli/usage/headless
# https://docs.aws.amazon.com/amplify/latest/userguide/environment-variables.html
# https://github.com/aws-amplify/amplify-console/issues/176
# https://github.com/aws-amplify/amplify-console/issues/229
# https://github.com/aws-amplify/amplify-console/issues/1642
# https://github.com/aws-amplify/amplify-console/issues/1330#issuecomment-739493860
version: 1
backend:
  phases:
    preBuild:
      commands:
        - yum update --assumeyes
        - yum install --assumeyes jq
        - echo "JQ_VERSION="$(jq --version)
        - node ./scripts/update_amplify_config.js
    build:
      commands:
        - '# Execute Amplify CLI with the helper script'
        - chmod u+x ./scripts/amplifyPush.sh
        - ./scripts/amplifyPush.sh --simple
frontend:
  phases:
    preBuild:
      commands:
        # - nvm install 14
        # - nvm use 14
        # https://stackoverflow.com/questions/58482655/what-is-the-closest-to-npm-ci-in-yarn
        - yarn global add ts-node
        - rm -rf node_modules && yarn install --frozen-lockfile # equivalent of `npm ci`
    build:
      commands:
        - yarn build

  artifacts:
    baseDirectory: build
    files:
      - '**/*'
  cache:
    paths:
      - ~/.cache
      # - node_modules/**/*
test:
  phases:
    preTest:
      commands:
        # https://docs.aws.amazon.com/amplify/latest/userguide/running-tests.html
        # https://aws.amazon.com/blogs/mobile/run-end-to-end-cypress-tests-for-your-fullstack-ci-cd-deployment-with-amplify-console/
        # https://github.com/aws-amplify/amplify-console/issues/583
        # https://github.com/aws-amplify/amplify-console/issues/240
        # https://github.com/cypress-io/cypress/issues/6960
        # - export PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
        # - fs.inotify.max_user_watches=524288
        # - yarn global add pm2 mocha mochawesome mochawesome-merge mochawesome-report-generator
        - yarn pm2 start 'yarn start:test'
        - yarn wait-on http://localhost:3000
    test:
      commands:
        # https://docs.cypress.io/guides/guides/command-line#cypress-run-config-lt-config-gt
        - 'yarn cypress run --config watchForFileChanges=false --reporter mochawesome --reporter-options "reportDir=cypress/report/mochawesome-report,overwrite=false,html=false,json=true,timestamp=mmddyyyy_HHMMss"'
    postTest:
      commands:
        - yarn mochawesome-merge cypress/report/mochawesome-report/*.json > cypress/report/mochawesome.json
        - yarn pm2 kill
  artifacts:
    baseDirectory: cypress
    configFilePath: '**/mochawesome.json'
    files:
      - '**/*.png'
      - '**/*.mp4'

Additional information

No response

adi-works avatar Jul 28 '21 22:07 adi-works

This is not something we currently support - but there may be a potential workaround for you in some of the comments here: https://github.com/aws-amplify/amplify-cli/issues/2792

ganipcanot avatar Jul 28 '21 23:07 ganipcanot

What?? what do you mean? how do previews suppose to work without this? the issue you linked to is not even relevant, it's just a client-side hack. My issue is with Cognito, it's not aware of the URL created for the preview build. For example, a branch with the name "sonic" would have this URL: https://sonic.{app-id}.amplifyapp.com. It's supposed to update Cognito when it deploys to that URL.

adi-works avatar Jul 29 '21 07:07 adi-works

Until this issue is handled more seriously, I worked around it by updating auth parameters.json in the preBuild phase. It's hacky, but it works. Replace prod and dev with your own user-generated environments.

// ./scripts/update_amplify_config.js

const fs = require('fs');
const path = require('path');

const { AWS_APP_ID, AWS_BRANCH_ARN } = process.env;
// get branch name based on amazon resource name (ARN), which
// is compatible with both branch auto-detection and previews.
// AWS_BRANCH_ARN: 'arn:aws:amplify:{region}:{account-id}:apps/{app-id}/branches/{branch-name}'
// branch-name will be "pr-x" for previews or the branch name for branch auto-detection.
const AWS_BRANCH = AWS_BRANCH_ARN.split('/').pop();

async function main() {
  console.log(`updating amplify config for branch "${AWS_BRANCH}"...`);
  // update callback/logout redirect urls for build url
  if (!['prod', 'dev'].includes(AWS_BRANCH)) {
    const backendConfig = require(path.resolve('./amplify/backend/backend-config.json'));
    const authResourceName = Object.keys(backendConfig.auth)[0];
    const authParametersJsonPath = path.resolve(`./amplify/backend/auth/${authResourceName}/parameters.json`);
    const authParametersJson = require(authParametersJsonPath);
    const oAuthMetadata = JSON.parse(authParametersJson.oAuthMetadata);
    oAuthMetadata.CallbackURLs.pop();
    oAuthMetadata.LogoutURLs.pop();
    oAuthMetadata.CallbackURLs.push(`https://${AWS_BRANCH}.${AWS_APP_ID}.amplifyapp.com/`);
    oAuthMetadata.LogoutURLs.push(`https://${AWS_BRANCH}.${AWS_APP_ID}.amplifyapp.com/`);
    authParametersJson.oAuthMetadata = JSON.stringify(oAuthMetadata);
    fs.writeFileSync(authParametersJsonPath, JSON.stringify(authParametersJson, null, 4));
  }
}

main();
version: 1
backend:
  phases:
    preBuild:
      commands:
        - node ./scripts/update_amplify_config.js

adi-works avatar Jul 29 '21 12:07 adi-works

three years later - amplify gen2 has the same problem, with all advertised full stack branch deployments and dynamic front-end previews - https://docs.amplify.aws/react/deploy-and-host/fullstack-branching/branch-deployments - none of that would work with call back urls hardcoded in the Cognito user pool client resource

https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpoolclient.html#cfn-cognito-userpoolclient-callbackurls

Amplify team, you must have tested a website with idP (social login) using branch deployments and previews in the gen2?

Did you notice those deployments get broken and require a redesign how callbackUrls gets populated?

OperationalFallacy avatar Jun 22 '24 17:06 OperationalFallacy