Skip to content

Commit

Permalink
Gracefully handle a missing subprocess module
Browse files Browse the repository at this point in the history
As reported in #773, it seems that certain sandboxed environments like
CloudFlare Workers don't provide a `subprocess` module, and that causes
Node to throw when we try to require it.

Because the only thing we need `subprocess` for is getting `uname`, here
we extend the already-existing infrastructure built to gracefully handle
errors to also be able to handle this new error case.

Fixes #773.
  • Loading branch information
brandur committed Jan 22, 2020
1 parent 20158db commit 64b4b9f
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
20 changes: 19 additions & 1 deletion lib/utils.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,23 @@
'use strict';

const EventEmitter = require('events').EventEmitter;
const exec = require('child_process').exec;
const qs = require('qs');
const crypto = require('crypto');

const hasOwn = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop);

// Certain sandboxed environments (our known example right now are CloudFlare
// Workers) may make `child_process` unavailable. Because `exec` isn't critical
// to the operation of stripe-node, we handle this unavailability gracefully.
var exec = null;
try {
exec = require('child_process').exec;
} catch (e) {
if (e.code !== 'MODULE_NOT_FOUND') {
throw e;
}
}

const OPTIONS_KEYS = [
'apiKey',
'idempotencyKey',
Expand Down Expand Up @@ -340,6 +351,13 @@ const utils = (module.exports = {
* This unifies that interface.
*/
safeExec: (cmd, cb) => {
// Occurs if we couldn't load the `child_process` module, which might
// happen in certain sandboxed environments like a CloudFlare Worker.
if (utils._exec === null) {
cb(new Error('exec not available'), null);
return;
}

try {
utils._exec(cmd, cb);
} catch (e) {
Expand Down
14 changes: 14 additions & 0 deletions test/utils.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -506,6 +506,20 @@ describe('utils', () => {
utils.safeExec('hello', myCb);
expect(calls).to.deep.equal([[myErr, null]]);
});

it ('handles being unable to require `child_process`', () => {
utils._exec = null;

var actualErr = null;
var actualRes = null;
function myCb(err, res) {
actualErr = err;
actualRes = res;
}
utils.safeExec('hello', myCb);
expect(actualErr.toString()).to.equal(new Error('exec not available').toString());
expect(actualRes).to.equal(null);
});
});

describe('flattenAndStringify', () => {
Expand Down

0 comments on commit 64b4b9f

Please sign in to comment.