cloudant / nodejs-cloudant

Cloudant Node.js client library
Apache License 2.0
255 stars 90 forks source link

Fix constant token renewal in the absence of a cookie Max-Age #427

Closed markusd closed 4 years ago

markusd commented 4 years ago

Checklist

Description

The TokenManager supports auto renewal of tokens. It uses the Max-Age field of the cookie header or a default value to schedule a callback for the renewal.

Fixes #426

Approach

The problem is that the default value is only used for the first renewal. For subsequent renewals the default is undefined so the renewal is scheduled instantly unless a Max-Age field is found in the header:

  _autoRenew(defaultMaxAgeSecs) {
    debug('Auto renewing token now...');
    this._renew().then((response) => {
      let maxAgeSecs = cookie.parse(response.headers['set-cookie'][0])['Max-Age'] || defaultMaxAgeSecs;
      let delayMSecs = maxAgeSecs / 2 * 1000;
      debug(`Renewing token in ${delayMSecs} milliseconds.`);
      setTimeout(this._autoRenew.bind(this), delayMSecs).unref(); <-- defaultMaxAgeSecs not passed on
    }).catch((error) => {
      debug(`Failed to auto renew token - ${error}. Retrying in 60 seconds.`);
      setTimeout(this._autoRenew.bind(this), 60000).unref();
    });
  }

The fix is to pass the defaultMaxAgeSecs on to the setTimeout handler.

Schema & API Changes