Skip to content

Commit

Permalink
SNOW-984450: Set ESLint rules to error (snowflakedb#733)
Browse files Browse the repository at this point in the history
  • Loading branch information
sfc-gh-pbulawa authored Dec 21, 2023
1 parent b092fb8 commit 7207966
Show file tree
Hide file tree
Showing 105 changed files with 2,092 additions and 2,642 deletions.
10 changes: 5 additions & 5 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ module.exports = {
'arrow-spacing': ['error'],
'block-spacing': ['error'],
'brace-style': ['error', '1tbs'],
'camelcase': ['warn'],
'camelcase': ['error'],
'comma-spacing': ['error'],
'curly': ['error', 'all'],
'eqeqeq': ['error', 'always', { 'null': 'ignore' }],
Expand All @@ -40,12 +40,12 @@ module.exports = {
'no-loss-of-precision': ['error'],
'no-mixed-spaces-and-tabs': ['error'],
'no-prototype-builtins': ['error'],
'no-redeclare': ['warn'],
'no-undef': ['warn'],
'no-unused-vars': ['warn'],
'no-redeclare': ['error'],
'no-undef': ['error'],
'no-unused-vars': ['error'],
'no-useless-catch': ['error'],
'no-useless-escape': ['error'],
'no-var': ['warn'],
'no-var': ['error'],
'object-curly-spacing': ['error', 'always'],
'prefer-const': ['error'],
'quotes': ['error', 'single'],
Expand Down
10 changes: 5 additions & 5 deletions lib/agent/cert_util.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ const MIN_CACHE_WARMUP_TIME_IN_MILLISECONDS = 18000000;
* @returns {*}
*/
exports.buildCertId = function (cert) {
var issuer = cert.issuerCertificate;
let issuer = cert.issuerCertificate;
cert = cert.raw;

try {
Expand All @@ -62,8 +62,8 @@ exports.buildCertId = function (cert) {
return null; // if we encountered an error during decoding, return null
}

var tbsCert = cert.tbsCertificate;
var tbsIssuer = issuer.tbsCertificate;
const tbsCert = cert.tbsCertificate;
const tbsIssuer = issuer.tbsCertificate;

const certID = {
hashAlgorithm: {
Expand Down Expand Up @@ -93,7 +93,7 @@ function sha1(data) {
* @returns {{cert: *, issuer: *}}
*/
exports.decode = function (cert) {
var issuer = cert.issuerCertificate;
let issuer = cert.issuerCertificate;
cert = cert.raw;

// note: this block might throw an error
Expand Down Expand Up @@ -193,7 +193,7 @@ const toUTCString = function (epochInMilliSeconds) {
* @param raws
*/
const findResponder = function (issuer, certs, raws) {
var issuerKey = issuer.tbsCertificate.subjectPublicKeyInfo;
let issuerKey = issuer.tbsCertificate.subjectPublicKeyInfo;
issuerKey = ocsp.utils.toPEM(
rfc5280.SubjectPublicKeyInfo.encode(issuerKey, 'der'), 'PUBLIC KEY');
if (certs.length > 0) {
Expand Down
8 changes: 4 additions & 4 deletions lib/agent/check.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ function getResponse(uri, req, cb) {

const chunks = [];
response.on('readable', function () {
var chunk = response.read();
const chunk = response.read();
if (!chunk) {
return;
}
Expand Down Expand Up @@ -169,16 +169,16 @@ module.exports = function check(options, cb, mock) {
}

function setOcspResponderUrl(uri) {
var parsedUrl = require('url').parse(process.env.SF_OCSP_RESPONSE_CACHE_SERVER_URL);
let parsedUrl = require('url').parse(process.env.SF_OCSP_RESPONSE_CACHE_SERVER_URL);

var targetUrl;
let targetUrl;
if (parsedUrl.port) {
targetUrl = `${parsedUrl.protocol}//${parsedUrl.hostname}:${parsedUrl.port}/retry`;
} else {
targetUrl = `${parsedUrl.protocol}//${parsedUrl.hostname}/retry`;
}

var b64data = req.data.toString('base64');
const b64data = req.data.toString('base64');
parsedUrl = require('url').parse(uri);

process.env.SF_OCSP_RESPONDER_URL = targetUrl + '/' + parsedUrl.hostname + '/' + b64data;
Expand Down
9 changes: 4 additions & 5 deletions lib/agent/https_ocsp_agent.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@
* Copyright (c) 2015-2019 Snowflake Computing Inc. All rights reserved.
*/

var Util = require('../util');
var HttpsAgent = require('https').Agent;
var SocketUtil = require('./socket_util');
const HttpsAgent = require('https').Agent;
const SocketUtil = require('./socket_util');

/**
* Creates a new HttpsOcspAgent.
Expand All @@ -15,7 +14,7 @@ var SocketUtil = require('./socket_util');
* @constructor
*/
function HttpsOcspAgent(options) {
var agent = HttpsAgent.apply(this, arguments);
const agent = HttpsAgent.apply(this, options);
agent.createConnection = function (port, host, options) {
// make sure the 'options' variables references the argument that actually
// contains the options
Expand All @@ -34,7 +33,7 @@ function HttpsOcspAgent(options) {
}

// call super
var socket = HttpsAgent.prototype.createConnection.apply(this, arguments);
const socket = HttpsAgent.prototype.createConnection.apply(this, arguments);

// secure the socket and return it
return SocketUtil.secureSocket(socket, host, null);
Expand Down
18 changes: 9 additions & 9 deletions lib/agent/ocsp_response_cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,20 +25,20 @@ const status = {
// validate input
const sizeLimit = GlobalConfig.getOcspResponseCacheSizeLimit();
// ocsp cache max age in second
var maxAgeSec = GlobalConfig.getOcspResponseCacheMaxAge();
let maxAgeSec = GlobalConfig.getOcspResponseCacheMaxAge();

Errors.assertInternal(Util.number.isPositiveInteger(sizeLimit));
Errors.assertInternal(Util.number.isPositiveInteger(maxAgeSec));

const cacheDir = GlobalConfig.mkdirCacheDir();
const cacheFileName = path.join(cacheDir, 'ocsp_response_cache.json');
// create a cache to store the responses, dynamically changes in size
var cache;
let cache;
// JSON object with previous cache's responses
var prevCacheObj;
let prevCacheObj;
// Cache updated time, in seconds, initialized as current time.
// Will be updated when load from local cache file or refresh by downloading
var cacheUpdateTimeSec = Date.now() / 1000;
let cacheUpdateTimeSec = Date.now() / 1000;

function deleteCache() {
try {
Expand Down Expand Up @@ -305,7 +305,7 @@ function OcspResponseCache() {
* @returns {Object}
*/
function validateCacheEntry(certIdBase64, ocspResponseBase64) {
var err;
let err;
if (ocspResponseBase64.length !== 2) {
Logger.getInstance()
.debug('OCSP cache value doesn\'t consist of two elements. Ignored.');
Expand Down Expand Up @@ -337,13 +337,13 @@ function OcspResponseCache() {

function updateCache(jsonObject) {
// Get the size of cache retrieved from the cache server
var responseCacheSize = Object.keys(jsonObject).length;
const responseCacheSize = Object.keys(jsonObject).length;

// Check if there are previous entries to append
if (prevCacheObj) {
// Count overlap between previous cache and response cache
// And delete entry if expired
var cacheOverlapCount = 0;
let cacheOverlapCount = 0;
for (const entry in jsonObject) {
if (entryExists(prevCacheObj, entry)) {
cacheOverlapCount++;
Expand All @@ -352,10 +352,10 @@ function OcspResponseCache() {
}

// Count entries from previous cache
var prevCacheSize = Object.keys(prevCacheObj).length;
const prevCacheSize = Object.keys(prevCacheObj).length;

// New cache size = previous cache size + response cache size - overlap between the two caches
var newCacheSize = prevCacheSize + responseCacheSize - cacheOverlapCount;
const newCacheSize = prevCacheSize + responseCacheSize - cacheOverlapCount;

// Create cache using new cache size if it doesn't exceed the upper limit
cache = new SimpleCache({ maxSize: newCacheSize < sizeLimit ? newCacheSize : sizeLimit });
Expand Down
4 changes: 2 additions & 2 deletions lib/agent/socket_util.js
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ exports.canEarlyExitForOCSP = canEarlyExitForOCSP;
*/
function validateCertChain(cert, cb) {
// walk up the certificate chain and collect all the certificates in an array
var certs = [];
const certs = [];
while (cert && cert.issuerCertificate &&
(cert.fingerprint !== cert.issuerCertificate.fingerprint)) {
certs.push(cert);
Expand All @@ -187,7 +187,7 @@ function validateCertChain(cert, cb) {

// create an array to store any errors encountered
// while validating the certificate chain
var errors = new Array(certs.length);
const errors = new Array(certs.length);

/**
* Called for every certificate as we traverse the certificate chain and
Expand Down
8 changes: 3 additions & 5 deletions lib/authentication/auth_default.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,7 @@
* @returns {Object}
* @constructor
*/
function auth_default(password) {
var password = password;

function AuthDefault(password) {
/**
* Update JSON body with password.
*
Expand All @@ -24,9 +22,9 @@ function auth_default(password) {
body['data']['PASSWORD'] = password;
};

this.authenticate = async function (authenticator, serviceName, account, username) {
this.authenticate = async function () {
return;
};
}

module.exports = auth_default;
module.exports = AuthDefault;
50 changes: 23 additions & 27 deletions lib/authentication/auth_keypair.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* Copyright (c) 2015-2021 Snowflake Computing Inc. All rights reserved.
*/

var util = require('../util');
const util = require('../util');

/**
* Creates a key-pair authenticator.
Expand All @@ -17,23 +17,19 @@ var util = require('../util');
* @returns {Object}
* @constructor
*/
function auth_keypair(privateKey, privateKeyPath, privateKeyPass, cryptomod, jwtmod, filesystem) {
var crypto = typeof cryptomod !== 'undefined' ? cryptomod : require('crypto');
var jwt = typeof jwtmod !== 'undefined' ? jwtmod : require('jsonwebtoken');
var fs = typeof filesystem !== 'undefined' ? filesystem : require('fs');
function AuthKeypair(privateKey, privateKeyPath, privateKeyPass, cryptomod, jwtmod, filesystem) {
const crypto = typeof cryptomod !== 'undefined' ? cryptomod : require('crypto');
const jwt = typeof jwtmod !== 'undefined' ? jwtmod : require('jsonwebtoken');
const fs = typeof filesystem !== 'undefined' ? filesystem : require('fs');

var privateKey = privateKey;
var privateKeyPath = privateKeyPath;
var privateKeyPass = privateKeyPass;
let jwtToken;

var jwtToken;

var LIFETIME = 120; // seconds
var ALGORITHM = 'RS256';
var ISSUER = 'iss';
var SUBJECT = 'sub';
var EXPIRE_TIME = 'exp';
var ISSUE_TIME = 'iat';
const LIFETIME = 120; // seconds
const ALGORITHM = 'RS256';
const ISSUER = 'iss';
const SUBJECT = 'sub';
const EXPIRE_TIME = 'exp';
const ISSUE_TIME = 'iat';

/**
* Update JSON body with token.
Expand All @@ -56,9 +52,9 @@ function auth_keypair(privateKey, privateKeyPath, privateKeyPass, cryptomod, jwt
*/
function loadPrivateKey(privateKeyPath, privateKeyPass) {
// Load private key file
var privateKeyFile = fs.readFileSync(privateKeyPath);
const privateKeyFile = fs.readFileSync(privateKeyPath);

var privateKeyObject;
let privateKeyObject;

// For encrypted private key
if (privateKeyPass) {
Expand All @@ -76,7 +72,7 @@ function auth_keypair(privateKey, privateKeyPath, privateKeyPass, cryptomod, jwt
});
}

var privateKey = privateKeyObject.export({
const privateKey = privateKeyObject.export({
format: 'pem',
type: 'pkcs8'
});
Expand All @@ -93,19 +89,19 @@ function auth_keypair(privateKey, privateKeyPath, privateKeyPass, cryptomod, jwt
*/
function calculatePublicKeyFingerprint(privateKey) {
// Extract public key object from private key
var pubKeyObject = crypto.createPublicKey({
const pubKeyObject = crypto.createPublicKey({
key: privateKey,
format: 'pem'
});

// Obtain public key string
var publicKey = pubKeyObject.export({
const publicKey = pubKeyObject.export({
format: 'der',
type: 'spki'
});

// Generate SHA256 hash of public key and encode in base64
var publicKeyFingerprint = 'SHA256:' +
const publicKeyFingerprint = 'SHA256:' +
crypto.createHash('sha256')
.update(publicKey, 'utf8')
.digest('base64');
Expand All @@ -124,7 +120,7 @@ function auth_keypair(privateKey, privateKeyPath, privateKeyPass, cryptomod, jwt
* @returns {null}
*/
this.authenticate = async function (authenticator, serviceName, account, username) {
var publicKeyFingerprint;
let publicKeyFingerprint;

// Use private key if already set in connection string, otherwise use private key file location
if (privateKey) {
Expand All @@ -137,11 +133,11 @@ function auth_keypair(privateKey, privateKeyPath, privateKeyPass, cryptomod, jwt
}

// Current time + 120 seconds
var currentTime = Date.now();
var jwtTokenExp = currentTime + LIFETIME;
const currentTime = Date.now();
const jwtTokenExp = currentTime + LIFETIME;

// Create payload containing jwt token and lifetime span
var payload = {
const payload = {
[ISSUER]: util.format('%s.%s.%s', account.toUpperCase(), username.toUpperCase(), publicKeyFingerprint),
[SUBJECT]: util.format('%s.%s', account.toUpperCase(), username.toUpperCase()),
[ISSUE_TIME]: currentTime,
Expand All @@ -153,4 +149,4 @@ function auth_keypair(privateKey, privateKeyPath, privateKeyPass, cryptomod, jwt
};
}

module.exports = auth_keypair;
module.exports = AuthKeypair;
8 changes: 3 additions & 5 deletions lib/authentication/auth_oauth.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,7 @@
* @returns {Object}
* @constructor
*/
function auth_oauth(token) {
var token = token;

function AuthOauth(token) {
/**
* Update JSON body with token.
*
Expand All @@ -24,9 +22,9 @@ function auth_oauth(token) {
body['data']['TOKEN'] = token;
};

this.authenticate = async function (authenticator, serviceName, account, username) {
this.authenticate = async function () {
return;
};
}

module.exports = auth_oauth;
module.exports = AuthOauth;
Loading

0 comments on commit 7207966

Please sign in to comment.