Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Setting NODE_TLS_REJECT_UNAUTHORIZED=0 doesn't work in jest@22+ #8449

Closed
trivikr opened this issue May 9, 2019 · 21 comments
Closed

Setting NODE_TLS_REJECT_UNAUTHORIZED=0 doesn't work in jest@22+ #8449

trivikr opened this issue May 9, 2019 · 21 comments

Comments

@trivikr
Copy link
Contributor

trivikr commented May 9, 2019

💥 Regression Report

A clear and concise description of what the regression is.

Last working version

Worked up to version: [email protected]
Stopped working in version: [email protected]

To Reproduce

Steps to reproduce the behavior:

  • Clone repo https:/trivikr/jest-self-signed-certificate
  • cd jest-self-signed-certificate
  • Change to jest-21 branch by running git checkout jest-21
  • npm test is successful
  • Change to master branch by running git checkout master
  • npm test fails

Expected behavior

I expected test to succeed, it fails with:

 FAIL  src/__tests__/server.test.js
  server
    ✕ server sends response (38ms)

  ● server › server sends response

    self signed certificate

Link to repl or repo (highly encouraged)

https:/trivikr/jest-self-signed-certificate

Run npx envinfo --preset jest

Paste the results here:

npx: installed 1 in 1.231s

  System:
    OS: macOS High Sierra 10.13.6
    CPU: (4) x64 Intel(R) Core(TM) i7-5557U CPU @ 3.10GHz
  Binaries:
    Node: 12.1.0 - /usr/local/bin/node
    Yarn: 1.15.2 - /usr/local/bin/yarn
    npm: 6.9.0 - /usr/local/bin/npm
  npmPackages:
    jest: ^24.8.0 => 24.8.0 

Ref: aws/aws-sdk-js-v3#244

@trivikr trivikr changed the title Setting NODE_TLS_REJECT_UNAUTHORIZED=0 doesn't work in jest@24 Setting NODE_TLS_REJECT_UNAUTHORIZED=0 doesn't work in jest@22+ May 9, 2019
@trivikr
Copy link
Contributor Author

trivikr commented May 20, 2019

Hi, is there any update on this regression?
Or any proposed solution to test https server by setting NODE_TLS_REJECT_UNAUTHORIZED=0

This might block users from updating past Jest v21

@dazraf
Copy link

dazraf commented May 23, 2019

This is a blocker for us. We're trying not to have a flag in our services to turn off SSL. For testing, we have to use self-signed certs. Pretty much a dealbreaker :-(

@trivikr
Copy link
Contributor Author

trivikr commented May 23, 2019

I tried to require server after setting environment variable in commit trivikr/jest-self-signed-certificate@864ef96 (under the assumption that update in process.env variables apply only for subsequent require statement)

The issue still exists

@trivikr
Copy link
Contributor Author

trivikr commented May 29, 2019

Any update on this regression?

@Ugzuzg
Copy link

Ugzuzg commented Jun 5, 2019

Having the same issue.

@trivikr
Copy link
Contributor Author

trivikr commented Jun 5, 2019

Hi team, any suggestion on how to work around the regression to write the unit test?
Requiring modules after setting environment variable doesn't work as explained in #8449 (comment)

@jeysal
Copy link
Contributor

jeysal commented Jun 8, 2019

After some experimenting/debugging, I tbh still have no idea why Node doesn't pick up the setting or which change in v22 could have introduced this. As a workaround it seems that it works if you launch Jest with the env var set to 0 straight away. If it's just a few tests that need this, could also consider doing a separate Jest run for those if you don't want to set it for all tests.

@Ugzuzg
Copy link

Ugzuzg commented Jun 8, 2019

It looks like it doesn't pick up any change to process.env not only to NODE_TLS_REJECT_UNAUTHORIZED.

@trivikr
Copy link
Contributor Author

trivikr commented Jun 27, 2019

Any update on this request?

@aballaci
Copy link

for me
export NODE_TLS_REJECT_UNAUTHORIZED=0 worked
set NODE_TLS_REJECT_UNAUTHORIZED=0 did not

@ppiyush13
Copy link

any update on this issue ?

@alvis
Copy link

alvis commented Apr 13, 2020

After researching this problem, it appears that jest wraps the env object with a proxy. Hence, any change on process.env would not be propagated to the real one.

https:/facebook/jest/blob/c83051789cc60789f2c575374270236e3a428879/packages/jest-util/src/createProcessObject.ts#L82-L128

I ended up solving the problem by a monkey patching technique which enforces node trusting the self-signed root CA via syswide-cas. i.e.

import { addCAs } from 'syswide-cas';

addCAs('path/to/rootCA.crt');

@akopchinskiy
Copy link

Any updates?

@styrus
Copy link

styrus commented Jun 2, 2020

Hi ,
I am also facing same issue. When running test using JEST. I am getting FetchError: request to URL/login failed, reason: self signed certificate in certificate chain

Note I am able tto run same test using Jasmine with setting
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

I have opened this issue please check. If any suggestions to resolve it.
jest-community/vscode-jest#592

@learngi
Copy link

learngi commented Sep 3, 2020

for me
export NODE_TLS_REJECT_UNAUTHORIZED=0 worked
set NODE_TLS_REJECT_UNAUTHORIZED=0 did not
Hi, can you please tell me where can I do that?

@silverwind
Copy link
Contributor

Doing the same in a setup file also seems to have no effect:

jest.config.js:

module.exports = {
  setupFiles: "./setup.js",
};

setup.js:

process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

@chris-buesser
Copy link

Hey I found a workaround for this in jest 26 (if you are using jsdom). You are going to have to create a custom environment to run jest in which extends jsdom. With the upgrade to jsdom 16, jest is not aware of the "resources" option on the JSDOM constructor, this and a combination of a regression somewhere with process.env which some of this thread has picked up on doesnt allow NODE_TLS_REJECT_UNAUTHORIZED=0 to work anymore.

Steps to patch:

  1. create a custom jsdom environment (save this as custom-jsdom-env.js next to package.json). This is similiar to the jest-environment-jsdom which ships with jest HOWEVER, it includes the "resources" component of JSDOM with the strictSSL set to false, there are two other options in the resources which you can find on jsdom but I have just set this one.
// custom-jsdom-environment
const JSDOMEnvironment = require('jest-environment-jsdom')
const { ResourceLoader, JSDOM, VirtualConsole } = require('jsdom')
const { installCommonGlobals } = require('jest-util')
const { ModuleMocker } = require('jest-mock')
const { LegacyFakeTimers, ModernFakeTimers } = require('@jest/fake-timers')

class CustomEnvironment extends JSDOMEnvironment {
  constructor(config, context) {
    super(config, context)

    this.dom = new JSDOM('<!DOCTYPE html>', {
      pretendToBeVisual: true,
      runScripts: 'dangerously',
      url: config.testURL,
      virtualConsole: new VirtualConsole().sendTo(context.console || console),
      ...config.testEnvironmentOptions,
      resources: new ResourceLoader({ strictSSL: false }),
    })
    const global = (this.global = this.dom.window.document.defaultView)

    if (!global) {
      throw new Error('JSDOM did not return a Window object')
    }

    // for "universal" code (code should use `globalThis`)
    global.global = global

    // Node's error-message stack size is limited at 10, but it's pretty useful
    // to see more than that when a test fails.
    this.global.Error.stackTraceLimit = 100
    installCommonGlobals(global, config.globals)

    // Report uncaught errors.
    this.errorEventListener = (event) => {
      if (userErrorListenerCount === 0 && event.error) {
        process.emit('uncaughtException', event.error)
      }
    }
    global.addEventListener('error', this.errorEventListener)

    // However, don't report them as uncaught if the user listens to 'error' event.
    // In that case, we assume the might have custom error handling logic.
    const originalAddListener = global.addEventListener
    const originalRemoveListener = global.removeEventListener
    let userErrorListenerCount = 0
    global.addEventListener = function(...args) {
      if (args[0] === 'error') {
        userErrorListenerCount++
      }
      return originalAddListener.apply(this, args)
    }
    global.removeEventListener = function(...args) {
      if (args[0] === 'error') {
        userErrorListenerCount--
      }
      return originalRemoveListener.apply(this, args)
    }

    this.moduleMocker = new ModuleMocker(global)

    const timerConfig = {
      idToRef: (id) => id,
      refToId: (ref) => ref,
    }

    this.fakeTimers = new LegacyFakeTimers({
      config,
      global,
      moduleMocker: this.moduleMocker,
      timerConfig,
    })

    this.fakeTimersModern = new ModernFakeTimers({ config, global })
  }

  async setup() {
    await super.setup()
  }

  async teardown() {
    await super.teardown()
  }

  runScript(script) {
    return super.runScript(script)
  }
}

module.exports = CustomEnvironment
  1. Add the testEnvironment to jest settings:
    You need to set the testEnvironment option to {PATH_TO}/cutom-jsdom-env.js or the --env={PATH_TO}/custom-jsdom-env.js

@StringEpsilon
Copy link
Contributor

Duplicate of #5118

@SimenB
Copy link
Member

SimenB commented Feb 27, 2022

Same as #9264 (comment).

If you really need to test this flag, I suggest doing what was suggested in #8449 (comment) (a separate run). You should be able to set this in a globalSetup as that's the real process.env and will be reflected in node core modules.


Note that if nodejs/node#31852 is every implemented, it might be possible we do something about this

@github-actions
Copy link

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Mar 30, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

15 participants